diff --git a/.changeset/alchemy-sourcemaps.md b/.changeset/alchemy-sourcemaps.md new file mode 100644 index 0000000000..bd20b3cf0a --- /dev/null +++ b/.changeset/alchemy-sourcemaps.md @@ -0,0 +1,5 @@ +--- +"@maple-dev/alchemy": minor +--- + +Automatic source map uploads. `@maple-dev/alchemy/vite` exports `mapleSourceMaps()`, a Vite plugin that turns on hidden source maps, gives each built JS file a debug id and moves the maps out of the deployed output into `.maple/sourcemaps/` with a manifest. The new `Maple.SourceMaps` resource uploads them through `POST /v2/source_maps` after the build, again only when the maps changed; deleting it keeps the uploaded maps, which earlier releases still need. `matchBy: "release"` uploads without debug ids, for telemetry that reports none. `MapleApiContract` gains `upload` for raw request bodies. diff --git a/.changeset/browser-exception-debug-ids.md b/.changeset/browser-exception-debug-ids.md new file mode 100644 index 0000000000..a5c61513b4 --- /dev/null +++ b/.changeset/browser-exception-debug-ids.md @@ -0,0 +1,5 @@ +--- +"@maple-dev/browser": minor +--- + +Exception events now carry `maple.exception.debug_ids`: for each script in the error's stack that registered a debug id (through `maple sourcemaps inject`, or Sentry's debug id tooling), its URL and id, so the matching source map is found by id rather than by file path. Absent when no script in the stack has one. diff --git a/.changeset/cli-sourcemaps.md b/.changeset/cli-sourcemaps.md new file mode 100644 index 0000000000..b7485c782f --- /dev/null +++ b/.changeset/cli-sourcemaps.md @@ -0,0 +1,5 @@ +--- +"@maple/cli": minor +--- + +New `maple sourcemaps inject ` and `maple sourcemaps upload `. `inject` gives every built JS file that has a source map a debug id (derived from the file and its map, so re-running changes nothing), registers it on the file's first line so errors thrown while the file loads still carry it, and writes it into the map; `--dry-run` reports without writing. Maps outside the build directory are never touched. `upload` sends each map to the logged-in workspace, once per JS file that uses it, matched by debug id or by `--service`, `--release` (defaults to the build directory's git commit) and the file path, with `--url-prefix` for the path the files are served under. Maps over 10 MiB (the largest Maple can symbolicate with) and index maps (`sections`) are skipped with a warning, and a run that uploads nothing fails. diff --git a/.gitignore b/.gitignore index 5433fe2984..9de8e42fd7 100644 --- a/.gitignore +++ b/.gitignore @@ -81,3 +81,6 @@ apps/ios/build/ scripts/seed-demo/.last-seed.json # isolated screenshot stack env, generated by bun run seed:demo:env .env.screenshots + +# Source maps the Vite plugin moves out of a build (`@maple-dev/alchemy/vite`). +.maple/ diff --git a/alchemy.run.ts b/alchemy.run.ts index 77ec2d8999..f4a4b880b6 100644 --- a/alchemy.run.ts +++ b/alchemy.run.ts @@ -47,6 +47,7 @@ import { createAwsSecurityBaseline } from "@maple/infra/security-baseline" import { optionalPlain, plainWithDefault, requiredPlain } from "@maple/infra/env" import * as Portless from "@maple/alchemy-portless" import { DEV_PROCESS_APPS, selectedDevApps, type DevApp } from "@maple/infra/dev-urls" +import { selfMapleProviders, uploadWebSourceMaps } from "@maple/infra/self-source-maps" import MapleAiLive, { MapleAi } from "./apps/ai/src/worker.ts" import Alerting from "./apps/alerting/src/worker.ts" import OrgEraser from "./apps/org-eraser/src/worker.ts" @@ -62,6 +63,8 @@ import { createMapleScraper } from "./apps/scraper/alchemy.run.ts" import Landing from "./apps/landing/src/worker.ts" import LocalUi from "./apps/local-ui/src/worker.ts" import Web from "./apps/web/src/worker.ts" +import { WEB_SERVICE_NAME } from "./apps/web/src/platform/service-identity.ts" +import { WEB_SOURCE_MAPS_DIR } from "./apps/web/source-maps-dir.ts" import { Array as Arr } from "effect" // Infisical defines CLOUDFLARE_DEFAULT_ACCOUNT_ID; alchemy reads CLOUDFLARE_ACCOUNT_ID. @@ -324,6 +327,8 @@ const providers = // Previews only; prd and dev deploys carry no NEON_API_KEY. Layer.provideMerge(!isDevServer && process.env.NEON_API_KEY ? Neon.providers() : Layer.empty), Layer.provideMerge(Portless.providers()), + // Uploads web's source maps; inert without the prd-only key. + Layer.provideMerge(selfMapleProviders), ) export default Alchemy.Stack( @@ -429,6 +434,14 @@ export default Alchemy.Stack( // A vite-source Worker: alchemy owns its build and dev server. Binds api as `API`. const web = yield* Effect.provideService(Web, ApiWorker, api) yield* serveWorker("web", web) + // Its source maps, moved out of the deployed assets by the Vite plugin (apps/web/vite.config.ts), + // uploaded after the build under the service and release its telemetry reports. + if (!isDevServer) + yield* uploadWebSourceMaps({ + dir: path.resolve(import.meta.dirname, WEB_SOURCE_MAPS_DIR), + service: WEB_SERVICE_NAME, + after: web.hash, + }) // StaticSites run their production build even on `alchemy dev`, so dev uses // `DEV_PROCESS_APPS` instead. Shared across instances: deployed by `us` alone. diff --git a/apps/cli/package.json b/apps/cli/package.json index 9f172b3028..880cb5a1a5 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -10,7 +10,7 @@ "start": "bun run src/bin.ts", "bench:ingest": "bun bench/ingest-http.ts", "bench:ingest:chdb": "bun bench/ingest-chdb.ts", - "test": "bun test --max-concurrency=1 test/*.test.ts src/core/*.test.ts", + "test": "bun test --max-concurrency=1 test/*.test.ts src/core/*.test.ts src/commands/*.test.ts", "typecheck": "tsrs --noEmit" }, "dependencies": { @@ -21,6 +21,7 @@ "@maple/local-server": "workspace:*", "@maple/promql": "workspace:*", "@maple/query-engine": "workspace:*", + "@maple/sourcemaps": "workspace:*", "effect": "catalog:effect" }, "devDependencies": { diff --git a/apps/cli/src/cli.ts b/apps/cli/src/cli.ts index 4662949ca2..c962a533e5 100644 --- a/apps/cli/src/cli.ts +++ b/apps/cli/src/cli.ts @@ -19,6 +19,7 @@ import { update } from "./commands/update" import { changelog } from "./commands/changelog" import { onboarding } from "./commands/onboarding" import { users, user, events } from "./commands/users" +import { sourcemaps } from "./commands/sourcemaps" import { OutputFormatSetting } from "./lib/output" // One CLI, two backends. Local mode runs the query-engine helpers against the @@ -91,5 +92,6 @@ export const cli = Command.make("maple").pipe( post, put, patch, + sourcemaps, ]), ) diff --git a/apps/cli/src/commands/sourcemaps.test.ts b/apps/cli/src/commands/sourcemaps.test.ts new file mode 100644 index 0000000000..521c9134f8 --- /dev/null +++ b/apps/cli/src/commands/sourcemaps.test.ts @@ -0,0 +1,67 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test" +import * as BunServices from "@effect/platform-bun/BunServices" +import { Effect, Option, String as Str } from "effect" +import { execFileSync } from "node:child_process" +import { mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { SourceMapUploadError } from "../core/sourcemaps-upload" +import { checkUploadOutcomes, gitHead } from "./sourcemaps" + +let dir = "" +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "maple-sourcemaps-cmd-")) +}) +afterEach(() => rmSync(dir, { recursive: true, force: true })) + +const git = (...args: ReadonlyArray) => + Str.trim(execFileSync("git", [...args], { cwd: dir, encoding: "utf8" })) + +describe("gitHead", () => { + test("reads the commit of the build directory's checkout, not the shell's", async () => { + git("init", "-q") + writeFileSync(join(dir, "a.txt"), "a") + git("add", "a.txt") + git("-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "-m", "init") + const buildHead = git("rev-parse", "HEAD") + const shellHead = Str.trim(execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" })) + + const head = await Effect.runPromise(Effect.provide(gitHead(dir), BunServices.layer)) + + expect(Option.getOrNull(head)).toBe(buildHead) + expect(buildHead).not.toBe(shellHead) + }) + + test("is none outside a git work tree", async () => { + const head = await Effect.runPromise(Effect.provide(gitHead(dir), BunServices.layer)) + expect(Option.isNone(head)).toBe(true) + }) +}) + +describe("checkUploadOutcomes", () => { + const skipped = { _tag: "skipped", minifiedPath: "a.js", reason: "no debug id" } as const + const uploaded = { + _tag: "uploaded", + minifiedPath: "b.js", + debugId: Option.none(), + sizeBytes: 1, + id: Option.none(), + } as const + + test("fails when every map was skipped, so CI does not go on without maps", async () => { + const error = await Effect.runPromise(Effect.flip(checkUploadOutcomes("dist", [skipped, skipped]))) + expect(error._tag).toBe("@maple/cli/UsageError") + expect(error.message).toBe("no source maps were uploaded; every matching map was skipped") + }) + + test("passes when at least one map went up, and reports a failed one", async () => { + await Effect.runPromise(checkUploadOutcomes("dist", [skipped, uploaded])) + const failed = { + _tag: "failed", + minifiedPath: "c.js", + error: new SourceMapUploadError({ message: "HTTP 400: bad", minifiedPath: "c.js", status: 400 }), + } as const + const error = await Effect.runPromise(Effect.flip(checkUploadOutcomes("dist", [uploaded, failed]))) + expect(error._tag).not.toBe("@maple/cli/UsageError") + }) +}) diff --git a/apps/cli/src/commands/sourcemaps.ts b/apps/cli/src/commands/sourcemaps.ts new file mode 100644 index 0000000000..7c247567f3 --- /dev/null +++ b/apps/cli/src/commands/sourcemaps.ts @@ -0,0 +1,186 @@ +import * as Argument from "effect/cli/Argument" +import * as Command from "effect/cli/Command" +import * as Flag from "effect/cli/Flag" +import { Array as Arr, Console, Effect, Option, Redacted, Stream, String as Str } from "effect" +import * as ChildProcess from "effect/process/ChildProcess" +import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner" +import { MapleConfig } from "../core/config" +import { injectDirectory, type InjectResult } from "../core/sourcemaps" +import { uploadDirectory, type UploadOutcome } from "../core/sourcemaps-upload" +import { ApiResponseError, ApiTransportError } from "./api" +import { CliUsageError } from "../lib/errors" + +const dirArg = Argument.Directory("dir", { mustExist: true }).pipe( + Argument.withDescription("Build output directory, e.g. dist"), +) + +const inject = Command.make("inject", { + dir: dirArg, + dryRun: Flag.Boolean("dry-run").pipe( + Flag.withDescription("Report what would change without writing any file"), + Flag.withDefault(false), + ), +}).pipe( + Command.withDescription( + "Add a debug id to every built JS file that has a source map, and to its map. Run after the build, before deploying and uploading; re-running changes nothing", + ), + Command.withHandler(({ dir, dryRun }) => + Effect.gen(function* () { + const results = yield* injectDirectory(dir, { dryRun }) + const verb = dryRun ? "would inject" : "injected" + const mapOf = (r: InjectResult) => Option.getOrElse(r.mapPath, () => "") + yield* Effect.forEach(results, (r) => { + switch (r.status) { + case "invalid_map": + return Console.error( + `warning: skipped ${r.file}: its source map ${mapOf(r)} is not a version 3 JSON object`, + ) + case "unsafe_map": + return Console.error( + `warning: skipped ${r.file}: its source map ${mapOf(r)} is outside ${dir}`, + ) + case "injected": + return Console.log(`${verb} ${r.file} (${Option.getOrElse(r.debugId, () => "")})`) + default: + return Effect.void + } + }) + const count = (status: string) => Arr.filter(results, (r) => r.status === status).length + yield* Console.log( + `${dryRun ? "Would inject" : "Injected"} ${count("injected")} file(s); skipped ${count("already_injected")} already injected, ${count("no_map")} without a source map` + + (count("invalid_map") > 0 ? `, ${count("invalid_map")} with an unreadable map` : "") + + (count("unsafe_map") > 0 ? `, ${count("unsafe_map")} with a map outside ${dir}` : ""), + ) + }), + ), +) + +/** The commit checked out where `dir` is, when it is inside a git work tree. */ +export const gitHead = (dir: string) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner + const handle = yield* spawner.spawn( + ChildProcess.make("git", ["rev-parse", "HEAD"], { + cwd: dir, + stdin: "ignore", + stdout: "pipe", + stderr: "ignore", + }), + ) + const [exitCode, stdout] = yield* Effect.all( + [handle.exitCode, Stream.mkString(Stream.decodeText(handle.stdout))], + { concurrency: "unbounded" }, + ) + const sha = Str.trim(stdout) + return exitCode === 0 && /^[0-9a-f]{40,64}$/.test(sha) ? Option.some(sha) : Option.none() + }).pipe( + Effect.scoped, + Effect.orElseSucceed(() => Option.none()), + ) + +const remoteTarget = Effect.gen(function* () { + const config = yield* MapleConfig + const target = Option.all({ apiUrl: config.apiUrl, token: config.token }) + if (Option.isNone(target)) + return yield* new CliUsageError({ + message: "not logged in to a Maple workspace", + hint: "run `maple login`, or set MAPLE_API_URL and MAPLE_API_TOKEN", + }) + return { apiUrl: target.value.apiUrl, token: Redacted.value(target.value.token) } +}) + +const formatBytes = (n: number): string => + n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MiB` : `${(n / 1024).toFixed(1)} KiB` + +const reportOutcome = (outcome: UploadOutcome): Effect.Effect => { + switch (outcome._tag) { + case "uploaded": + return Console.log( + `uploaded ${outcome.minifiedPath} (${formatBytes(outcome.sizeBytes)}${Option.match(outcome.debugId, { onNone: () => "", onSome: (id) => `, ${id}` })})`, + ) + case "skipped": + return Console.error(`warning: skipped ${outcome.minifiedPath}: ${outcome.reason}`) + case "failed": + return Console.error(`failed ${outcome.minifiedPath}: ${outcome.error.message}`) + } +} + +/** Fails the command when nothing was uploaded or an upload failed, so CI stops there. */ +export const checkUploadOutcomes = ( + dir: string, + outcomes: ReadonlyArray, +): Effect.Effect => + Effect.gen(function* () { + const count = (tag: UploadOutcome["_tag"]) => Arr.filter(outcomes, (o) => o._tag === tag).length + if (outcomes.length === 0) + return yield* new CliUsageError({ + message: `no source maps with a matching JS file found under ${dir}`, + hint: "build with source maps enabled, then run `maple sourcemaps inject` on the output", + }) + if (count("skipped") === outcomes.length) + return yield* new CliUsageError({ + message: "no source maps were uploaded; every matching map was skipped", + hint: "check the skip warnings above", + }) + const firstFailure = Arr.findFirst(outcomes, (o) => o._tag === "failed") + if (Option.isSome(firstFailure) && firstFailure.value._tag === "failed") { + // Reported as the raw API errors so a 4xx reads as the request to fix, not a CLI fault. + const failed = firstFailure.value.error + const message = `${count("failed")} source map upload(s) failed; first: ${failed.minifiedPath}: ${failed.message}` + if (failed.status === undefined) return yield* new ApiTransportError({ message }) + return yield* failed.status === 401 + ? new ApiResponseError({ status: 401, message, hint: "run `maple login` again" }) + : new ApiResponseError({ status: failed.status, message }) + } + }) + +const upload = Command.make("upload", { + dir: dirArg, + service: Flag.optional( + Flag.String("service").pipe( + Flag.withDescription("Service name the maps belong to (OTel service.name)"), + ), + ), + release: Flag.optional( + Flag.String("release").pipe( + Flag.withDescription( + "Release the maps belong to (OTel service.version); defaults to `git rev-parse HEAD` when --service is set", + ), + ), + ), + urlPrefix: Flag.optional( + Flag.String("url-prefix").pipe( + Flag.withDescription( + "Path the files are served under, prepended to each file path, e.g. assets/", + ), + ), + ), +}).pipe( + Command.withDescription( + "Upload every source map in a build directory to the logged-in workspace so error stack traces show original source", + ), + Command.withHandler(({ dir, service, release, urlPrefix }) => + Effect.gen(function* () { + const { apiUrl, token } = yield* remoteTarget + const version = Option.isSome(release) || Option.isNone(service) ? release : yield* gitHead(dir) + const outcomes = yield* uploadDirectory( + dir, + { apiUrl, token, service, version, urlPrefix, concurrency: 4 }, + reportOutcome, + ) + const count = (tag: UploadOutcome["_tag"]) => Arr.filter(outcomes, (o) => o._tag === tag).length + const bytes = Arr.reduce(outcomes, 0, (sum, o) => + o._tag === "uploaded" ? sum + o.sizeBytes : sum, + ) + yield* Console.log( + `Uploaded ${count("uploaded")} source map(s) (${formatBytes(bytes)}); ${count("skipped")} skipped, ${count("failed")} failed`, + ) + return yield* checkUploadOutcomes(dir, outcomes) + }), + ), +) + +export const sourcemaps = Command.make("sourcemaps").pipe( + Command.withDescription("Prepare and upload JavaScript source maps for readable error stack traces"), + Command.withSubcommands([inject, upload]), +) diff --git a/apps/cli/src/core/sourcemaps-upload.test.ts b/apps/cli/src/core/sourcemaps-upload.test.ts new file mode 100644 index 0000000000..16a77591c0 --- /dev/null +++ b/apps/cli/src/core/sourcemaps-upload.test.ts @@ -0,0 +1,183 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test" +import * as BunServices from "@effect/platform-bun/BunServices" +import { Array as Arr, Effect, Layer, Option, Record as Rec } from "effect" +import { FetchHttpClient } from "effect/http" +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { minifiedPathFor, uploadDirectory, type UploadOptions, type UploadOutcome } from "./sourcemaps-upload" + +interface Seen { + readonly url: URL + readonly authorization: string | null + readonly contentType: string | null + readonly body: string +} + +const servers: Array> = [] + +/** A local stand-in for `POST /v2/source_maps`, reached over the real fetch client. */ +const fakeServer = (answer: (url: URL) => Response) => { + const seen: Array = [] + const server = Bun.serve({ + port: 0, + fetch: async (request) => { + const url = new URL(request.url) + seen.push({ + url, + authorization: request.headers.get("authorization"), + contentType: request.headers.get("content-type"), + body: await request.text(), + }) + return answer(url) + }, + }) + servers.push(server) + return { seen, apiUrl: `http://127.0.0.1:${server.port}/` } +} + +const options = (overrides: Partial = {}): UploadOptions => ({ + apiUrl: "http://127.0.0.1:1/", + token: "maple_ak_test", + service: Option.none(), + version: Option.none(), + urlPrefix: Option.none(), + concurrency: 4, + ...overrides, +}) + +const upload = (dir: string, opts: UploadOptions) => + Effect.runPromise( + uploadDirectory(dir, opts, () => Effect.void).pipe( + Effect.provide(Layer.merge(FetchHttpClient.layer, BunServices.layer)), + ), + ) + +const ID = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" +const mapWithId = JSON.stringify({ version: 3, sources: [], names: [], mappings: "AAAA", debugId: ID }) + +let dir = "" +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "maple-sourcemaps-upload-")) +}) +afterEach(async () => { + rmSync(dir, { recursive: true, force: true }) + await Promise.all(Arr.map(servers.splice(0), (server) => server.stop(true))) +}) + +describe("minifiedPathFor", () => { + test("prepends the prefix with one slash and never starts with one", () => { + expect(minifiedPathFor(Option.some("assets/"), "index.js")).toBe("assets/index.js") + expect(minifiedPathFor(Option.some("/static"), "js/a.js")).toBe("static/js/a.js") + expect(minifiedPathFor(Option.none(), "a.js")).toBe("a.js") + }) +}) + +describe("uploadDirectory", () => { + test("posts each map as the raw body with its path, debug id, service and version", async () => { + mkdirSync(join(dir, "js")) + writeFileSync(join(dir, "js/index-Bx81.js"), `a()\n//# debugId=${ID}\n`) + writeFileSync(join(dir, "js/index-Bx81.js.map"), mapWithId) + writeFileSync(join(dir, "orphan.js.map"), mapWithId) + const server = fakeServer(() => + Response.json({ object: "source_map", id: "smap_1" }, { status: 201 }), + ) + + const outcomes = await upload( + dir, + options({ + apiUrl: server.apiUrl, + service: Option.some("web"), + version: Option.some("abc123"), + urlPrefix: Option.some("assets/"), + }), + ) + + expect(server.seen).toHaveLength(1) + const call = server.seen[0] + expect(call?.url.pathname).toBe("/v2/source_maps") + expect(Rec.fromEntries(Arr.fromIterable(call?.url.searchParams ?? []))).toEqual({ + minified_path: "assets/js/index-Bx81.js", + debug_id: ID, + service: "web", + version: "abc123", + }) + expect(call?.authorization).toBe("Bearer maple_ak_test") + expect(call?.body).toBe(mapWithId) + expect(call?.contentType).toBe("application/json") + expect(outcomes).toEqual([ + { + _tag: "uploaded", + minifiedPath: "assets/js/index-Bx81.js", + debugId: Option.some(ID), + sizeBytes: mapWithId.length, + id: Option.some("smap_1"), + }, + ]) + }) + + test("reads the debug id from the JS comment when the map has none", async () => { + writeFileSync(join(dir, "a.js"), `a()\n//# debugId=${ID}\n`) + writeFileSync(join(dir, "a.js.map"), JSON.stringify({ version: 3, mappings: "" })) + const server = fakeServer(() => Response.json({ id: "smap_2" })) + + await upload(dir, options({ apiUrl: server.apiUrl })) + + expect(server.seen[0]?.url.searchParams.get("debug_id")).toBe(ID) + expect(server.seen[0]?.url.searchParams.has("service")).toBe(false) + }) + + test("a refused upload carries the server's message and the rest still upload", async () => { + writeFileSync(join(dir, "bad.js"), "b()\n") + writeFileSync(join(dir, "bad.js.map"), JSON.stringify({ version: 3, mappings: "" })) + writeFileSync(join(dir, "good.js"), "g()\n") + writeFileSync(join(dir, "good.js.map"), mapWithId) + const server = fakeServer((url) => + url.searchParams.get("minified_path") === "bad.js" + ? Response.json({ error: { message: "mappings must be a string" } }, { status: 400 }) + : Response.json({ id: "smap_3" }), + ) + + const outcomes = await upload( + dir, + options({ apiUrl: server.apiUrl, service: Option.some("web"), version: Option.some("v1") }), + ) + + const byPath = Rec.fromEntries(Arr.map(outcomes, (o: UploadOutcome) => [o.minifiedPath, o] as const)) + const bad = byPath["bad.js"] + expect(bad?._tag).toBe("failed") + if (bad?._tag === "failed") { + expect(bad.error.status).toBe(400) + expect(bad.error.message).toBe("HTTP 400: mappings must be a string") + } + expect(byPath["good.js"]?._tag).toBe("uploaded") + }) + + test("skips a map with no debug id when there is no service and release to match it by", async () => { + writeFileSync(join(dir, "a.js"), "a()\n") + writeFileSync(join(dir, "a.js.map"), JSON.stringify({ version: 3, mappings: "" })) + const server = fakeServer(() => Response.json({ id: "smap_4" })) + + const outcomes = await upload(dir, options({ apiUrl: server.apiUrl, service: Option.some("web") })) + + expect(server.seen).toHaveLength(0) + expect(Arr.map(outcomes, (o) => o._tag)).toEqual(["skipped"]) + }) + + test("skips an index map, which the workspace refuses", async () => { + writeFileSync(join(dir, "a.js"), `a()\n//# debugId=${ID}\n`) + writeFileSync(join(dir, "a.js.map"), JSON.stringify({ version: 3, sections: [] })) + const server = fakeServer(() => Response.json({ id: "smap_5" })) + + const outcomes = await upload(dir, options({ apiUrl: server.apiUrl })) + + expect(server.seen).toHaveLength(0) + expect(outcomes).toEqual([ + { + _tag: "skipped", + minifiedPath: "a.js", + reason: "index source maps are not supported; emit a regular map", + }, + ]) + }) +}) diff --git a/apps/cli/src/core/sourcemaps-upload.ts b/apps/cli/src/core/sourcemaps-upload.ts new file mode 100644 index 0000000000..de703a9f00 --- /dev/null +++ b/apps/cli/src/core/sourcemaps-upload.ts @@ -0,0 +1,215 @@ +import { Array as Arr, Effect, Option, Result, Schema, String as Str } from "effect" +import { FileSystem } from "effect/FileSystem" +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http" +import { sendTraced } from "../commands/api" +import { errorMessageOf, parseJson } from "./api-request" +import { + existingDebugId, + findJsFiles, + isIndexMap, + mapDebugId, + mapUsers, + MAX_MAP_BYTES, + SourceMapsFileError, +} from "./sourcemaps" + +/** One map the workspace refused, or that never reached it (no `status`). */ +export class SourceMapUploadError extends Schema.TaggedError()( + "@maple/cli/SourceMapUploadError", + { + message: Schema.String, + minifiedPath: Schema.String, + status: Schema.optionalKey(Schema.Number), + cause: Schema.optionalKey(Schema.Defect()), + }, +) {} + +export interface UploadOptions { + readonly apiUrl: string + readonly token: string + readonly service: Option.Option + readonly version: Option.Option + readonly urlPrefix: Option.Option + /** Parallel uploads; the command uses 4. */ + readonly concurrency: number +} + +export type UploadOutcome = + | { + readonly _tag: "uploaded" + readonly minifiedPath: string + readonly debugId: Option.Option + readonly sizeBytes: number + readonly id: Option.Option + } + | { readonly _tag: "skipped"; readonly minifiedPath: string; readonly reason: string } + | { readonly _tag: "failed"; readonly minifiedPath: string; readonly error: SourceMapUploadError } + +/** The JS file's path on the deploy, `--url-prefix` first, never with a leading slash. */ +export const minifiedPathFor = (urlPrefix: Option.Option, file: string): string => { + const prefix = Option.getOrElse(urlPrefix, () => "") + const joined = prefix === "" || Str.endsWith("/")(prefix) ? `${prefix}${file}` : `${prefix}/${file}` + return Str.replace(/^(?:~\/|\/)+/, "")(joined) +} + +/** The query string for one upload: debug id, service and version only when known. */ +export const uploadParams = (input: { + readonly minifiedPath: string + readonly debugId: Option.Option + readonly service: Option.Option + readonly version: Option.Option +}): ReadonlyArray => [ + ["minified_path", input.minifiedPath], + ...Option.toArray(Option.map(input.debugId, (id) => ["debug_id", id] as const)), + ...Option.toArray(Option.map(input.service, (s) => ["service", s] as const)), + ...Option.toArray(Option.map(input.version, (v) => ["version", v] as const)), +] + +const IdField = Schema.Struct({ id: Schema.String }) + +const send = ( + options: UploadOptions, + params: ReadonlyArray, + minifiedPath: string, + body: Uint8Array, +) => + Effect.gen(function* () { + const client = yield* HttpClient.HttpClient + const url = new URL(`${Str.replace(/\/+$/, "")(options.apiUrl)}/v2/source_maps`) + const request = HttpClientRequest.post(url.toString()).pipe( + HttpClientRequest.setUrlParams(params), + HttpClientRequest.setHeader("accept", "application/json"), + HttpClientRequest.bearerToken(options.token), + HttpClientRequest.bodyUint8Array(body, "application/json"), + ) + const response = yield* sendTraced(client, request, url).pipe( + Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), + Effect.mapError( + (cause) => + new SourceMapUploadError({ + message: `could not reach ${url.origin}`, + minifiedPath, + cause, + }), + ), + ) + const text = yield* response.text.pipe(Effect.orElseSucceed(() => "")) + const json = text === "" ? Option.none() : Result.getSuccess(parseJson(text, "the response")) + if (response.status >= 200 && response.status < 300) + return Option.map( + Option.flatMap(json, (u) => Result.getSuccess(Schema.decodeUnknownResult(IdField)(u))), + (o) => o.id, + ) + const detail = Option.getOrElse(Option.flatMap(json, errorMessageOf), () => + Str.trim(text) === "" ? "no message" : Str.slice(0, 300)(Str.trim(text)), + ) + return yield* new SourceMapUploadError({ + message: `HTTP ${response.status}: ${detail}`, + minifiedPath, + status: response.status, + }) + }) + +/** + * Upload every map below `dir` whose JS file is there too, one upload per JS file. A map a file + * names outside `dir` is skipped, never read. `onOutcome` runs as each file finishes, + * so progress prints while the rest are still uploading. + */ +export const uploadDirectory = ( + dir: string, + options: UploadOptions, + onOutcome: (outcome: UploadOutcome) => Effect.Effect, +) => + Effect.gen(function* () { + const fs = yield* FileSystem + const files = yield* findJsFiles(dir) + const users = mapUsers(files) + const refused = Arr.flatMap(files, (js) => + Option.toArray( + Option.map(js.refusedMap, (mapPath): UploadOutcome => ({ + _tag: "skipped", + minifiedPath: minifiedPathFor(options.urlPrefix, js.file), + reason: `its source map ${mapPath} is outside ${dir}`, + })), + ), + ) + yield* Effect.forEach(refused, onOutcome, { discard: true }) + // A map two JS files share is uploaded once per file, each under its own path and id. + const withMaps = Arr.flatMap(files, (js) => + Option.toArray( + Option.map(js.mapPath, (mapPath) => ({ js, mapPath, shared: (users.get(mapPath) ?? 0) > 1 })), + ), + ) + const uploaded = yield* Effect.forEach( + withMaps, + ({ js, mapPath, shared }) => + Effect.gen(function* () { + const minifiedPath = minifiedPathFor(options.urlPrefix, js.file) + const info = yield* fs.stat(mapPath).pipe( + Effect.mapError( + (cause) => + new SourceMapsFileError({ + message: `could not read ${mapPath}`, + path: mapPath, + cause, + }), + ), + ) + if (info.size > BigInt(MAX_MAP_BYTES)) + return { + _tag: "skipped", + minifiedPath, + reason: `map is over ${MAX_MAP_BYTES / 1024 / 1024} MiB`, + } satisfies UploadOutcome + const body = yield* fs.readFile(mapPath).pipe( + Effect.mapError( + (cause) => + new SourceMapsFileError({ + message: `could not read ${mapPath}`, + path: mapPath, + cause, + }), + ), + ) + if (isIndexMap(new TextDecoder().decode(body))) + return { + _tag: "skipped", + minifiedPath, + reason: "index source maps are not supported; emit a regular map", + } satisfies UploadOutcome + // The file's own id is what its frames report; a shared map's id belongs to no one file. + const debugId = Option.orElse(existingDebugId(js.code), () => + shared ? Option.none() : mapDebugId(new TextDecoder().decode(body)), + ) + if ( + Option.isNone(debugId) && + (Option.isNone(options.service) || Option.isNone(options.version)) + ) + return { + _tag: "skipped", + minifiedPath, + reason: "no debug id; run `maple sourcemaps inject` first, or pass --service and --release", + } satisfies UploadOutcome + const params = uploadParams({ + minifiedPath, + debugId, + service: options.service, + version: options.version, + }) + return yield* send(options, params, minifiedPath, body).pipe( + Effect.map((id): UploadOutcome => ({ + _tag: "uploaded", + minifiedPath, + debugId, + sizeBytes: body.byteLength, + id, + })), + Effect.catchTag("@maple/cli/SourceMapUploadError", (error) => + Effect.succeed({ _tag: "failed", minifiedPath, error }), + ), + ) + }).pipe(Effect.tap(onOutcome)), + { concurrency: options.concurrency }, + ) + return [...refused, ...uploaded] + }) diff --git a/apps/cli/src/core/sourcemaps.test.ts b/apps/cli/src/core/sourcemaps.test.ts new file mode 100644 index 0000000000..95bb6308c9 --- /dev/null +++ b/apps/cli/src/core/sourcemaps.test.ts @@ -0,0 +1,449 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test" +import * as BunServices from "@effect/platform-bun/BunServices" +import { Array as Arr, Effect, Layer, Option, Result, String as Str } from "effect" +import { FileSystem } from "effect/FileSystem" +import * as PlatformError from "effect/PlatformError" +import { FetchHttpClient } from "effect/http" +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { canPrepend, debugIdFor, debugIdSnippet, existingDebugId, injectDirectory } from "./sourcemaps" +import { uploadDirectory } from "./sourcemaps-upload" + +const run = (effect: Effect.Effect) => + Effect.runPromise(Effect.provide(effect, BunServices.layer)) + +const map = (file: string, extra: Record = {}) => + JSON.stringify({ + version: 3, + file, + sources: ["../src/a.ts"], + names: [], + mappings: "AAAA,SAAS;AACT", + ...extra, + }) + +const read = (path: string) => readFileSync(path, "utf8") + +let dir = "" +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "maple-sourcemaps-")) +}) +afterEach(() => rmSync(dir, { recursive: true, force: true })) + +const DIGITS = new Map( + Arr.map( + Arr.fromIterable("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), + (c, i) => [c, i] as const, + ), +) + +/** The original (0-based) line the first segment of generated line `line` (1-based) maps to. */ +const originalLineAt = (mappings: string, line: number): number | undefined => { + const decode = (segment: string): ReadonlyArray => { + const values: Array = [] + const state = { value: 0, shift: 0 } + Arr.forEach(Arr.fromIterable(segment), (char) => { + const digit = DIGITS.get(char) ?? 0 + state.value += (digit & 31) << state.shift + state.shift += 5 + if ((digit & 32) === 0) { + values.push((state.value & 1) === 1 ? -(state.value >>> 1) : state.value >>> 1) + state.value = 0 + state.shift = 0 + } + }) + return values + } + // Source lines are deltas across the whole mappings string. + const lines = Str.split(";")(mappings) + const sourceLine = { value: 0 } + const found = { value: undefined as number | undefined } + Arr.forEach(lines, (generated, i) => { + Arr.forEach(generated === "" ? [] : Str.split(",")(generated), (segment, j) => { + const fields = decode(segment) + sourceLine.value += fields[2] ?? 0 + if (i === line - 1 && j === 0) found.value = sourceLine.value + }) + }) + return found.value +} + +describe("debugIdFor", () => { + test("is a lowercase UUID of the JS and its map, never of the map's own debug id", () => { + const id = debugIdFor("console.log(1)\n", map("a.js")) + expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/) + expect(debugIdFor("console.log(1)\n", map("a.js"))).toBe(id) + expect(debugIdFor("console.log(2)\n", map("a.js"))).not.toBe(id) + expect(debugIdFor("console.log(1)\n", map("a.js", { debugId: id, debug_id: id }))).toBe(id) + }) +}) + +describe("injectDirectory", () => { + test("registers first, tags the end and shifts the map one line", async () => { + mkdirSync(join(dir, "assets")) + const withUrl = "function a(){return 1}\n//# sourceMappingURL=index.js.map\n" + const bare = "export const b=2;" + writeFileSync(join(dir, "assets/index.js"), withUrl) + writeFileSync(join(dir, "assets/index.js.map"), map("index.js", { mappings: "AAAA;AACA" })) + writeFileSync(join(dir, "chunk.mjs"), bare) + writeFileSync(join(dir, "chunk.mjs.map"), map("chunk.mjs")) + writeFileSync(join(dir, "nomap.cjs"), "module.exports=1\n") + + const results = await run(injectDirectory(dir, { dryRun: false })) + + const idA = debugIdFor(withUrl, map("index.js", { mappings: "AAAA;AACA" })) + const idB = debugIdFor(bare, map("chunk.mjs")) + expect(read(join(dir, "assets/index.js"))).toBe( + `${debugIdSnippet(idA)}\nfunction a(){return 1}\n//# debugId=${idA}\n//# sourceMappingURL=index.js.map\n`, + ) + expect(read(join(dir, "chunk.mjs"))).toBe( + `${debugIdSnippet(idB)}\nexport const b=2;\n//# debugId=${idB}\n`, + ) + expect(read(join(dir, "nomap.cjs"))).toBe("module.exports=1\n") + + const mapA = JSON.parse(read(join(dir, "assets/index.js.map"))) + expect(mapA).toEqual({ + ...JSON.parse(map("index.js")), + mappings: ";AAAA;AACA", + debugId: idA, + debug_id: idA, + x_maple_shifted: idA, + }) + // `function a` was generated line 1 (original line 0) and is line 2 now; the next line follows. + expect([originalLineAt("AAAA;AACA", 1), originalLineAt("AAAA;AACA", 2)]).toEqual([0, 1]) + expect([ + originalLineAt(mapA.mappings, 1), + originalLineAt(mapA.mappings, 2), + originalLineAt(mapA.mappings, 3), + ]).toEqual([undefined, 0, 1]) + + expect(Arr.map(results, (r) => [r.file, r.status])).toEqual([ + ["assets/index.js", "injected"], + ["chunk.mjs", "injected"], + ["nomap.cjs", "no_map"], + ]) + }) + + test("appends after a shebang, a directive prologue or for an index map, leaving mappings alone", async () => { + const shebang = "#!/usr/bin/env node\nrun()\n" + const strict = '/*! license */\n"use strict";\nrun()\n' + const single = "'use client';\nrun()\n" + const indexed = "run()\n" + const sections = { + mappings: undefined, + sections: [{ offset: { line: 0, column: 0 }, map: JSON.parse(map("i.js")) }], + } + writeFileSync(join(dir, "a.js"), shebang) + writeFileSync(join(dir, "a.js.map"), map("a.js")) + writeFileSync(join(dir, "b.js"), strict) + writeFileSync(join(dir, "b.js.map"), map("b.js")) + writeFileSync(join(dir, "c.js"), single) + writeFileSync(join(dir, "c.js.map"), map("c.js")) + writeFileSync(join(dir, "i.js"), indexed) + writeFileSync(join(dir, "i.js.map"), map("i.js", sections)) + + const results = await run(injectDirectory(dir, { dryRun: false })) + const ids = Arr.map(results, (r) => Option.getOrElse(r.debugId, () => "")) + Arr.forEach([shebang, strict, single, indexed], (code, i) => { + const file = ["a.js", "b.js", "c.js", "i.js"][i] ?? "" + const id = ids[i] ?? "" + expect(read(join(dir, file))).toBe(`${code}${debugIdSnippet(id)}\n//# debugId=${id}\n`) + }) + expect(JSON.parse(read(join(dir, "a.js.map"))).mappings).toBe("AAAA,SAAS;AACT") + expect(JSON.parse(read(join(dir, "i.js.map"))).sections).toHaveLength(1) + + const again = await run(injectDirectory(dir, { dryRun: false })) + expect(Arr.map(again, (r) => [r.status, r.mapUpdated])).toEqual( + Arr.makeBy(4, () => ["already_injected", false]), + ) + }) + + test("reads a directive prologue past comments in one linear pass", () => { + expect(canPrepend('/*! a */\n// b\n "use strict";\nrun()')).toBe(false) + expect(canPrepend("/* a */ run('x')")).toBe(true) + const started = performance.now() + canPrepend(Str.repeat(100_000)("/*")) + canPrepend(`${Str.repeat(100_000)(" ")}x`) + expect(performance.now() - started).toBeLessThan(50) + }) + + test("converges after a failed JS write or a failed map write, moving the map once", async () => { + const code = "boom()\n" + const original = map("a.js", { mappings: "AAAA;AACA" }) + const failing = (failsOn: (path: string) => boolean) => + Layer.effect( + FileSystem, + Effect.gen(function* () { + const fs = yield* FileSystem + return { + ...fs, + writeFileString: ( + path: string, + data: string, + options?: Parameters[2], + ) => + failsOn(path) + ? Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "FileSystem", + method: "writeFileString", + }), + ) + : fs.writeFileString(path, data, options), + } + }), + ).pipe(Layer.provideMerge(BunServices.layer)) + const injectWith = (failsOn: (path: string) => boolean) => + Effect.runPromise( + Effect.provide(Effect.result(injectDirectory(dir, { dryRun: false })), failing(failsOn)), + ) + const mappings = () => JSON.parse(read(join(dir, "a.js.map"))).mappings + + // The JS write fails after the map was moved: the next run must not move it again. + writeFileSync(join(dir, "a.js"), code) + writeFileSync(join(dir, "a.js.map"), original) + expect(Result.isFailure(await injectWith((path) => Str.endsWith("a.js")(path)))).toBe(true) + expect(read(join(dir, "a.js"))).toBe(code) + expect(mappings()).toBe(";AAAA;AACA") + const [repaired] = await run(injectDirectory(dir, { dryRun: false })) + const id = Option.getOrNull(repaired?.debugId ?? Option.none()) + expect(read(join(dir, "a.js"))).toBe(`${debugIdSnippet(id ?? "")}\nboom()\n//# debugId=${id}\n`) + expect(mappings()).toBe(";AAAA;AACA") + expect(JSON.parse(read(join(dir, "a.js.map"))).debugId).toBe(id) + const [again] = await run(injectDirectory(dir, { dryRun: false })) + expect([again?.status, again?.mapUpdated, mappings()]).toEqual([ + "already_injected", + false, + ";AAAA;AACA", + ]) + + // The map write fails: nothing changes, and the next run injects as if the first never ran. + writeFileSync(join(dir, "a.js"), code) + writeFileSync(join(dir, "a.js.map"), original) + expect(Result.isFailure(await injectWith((path) => Str.includes("a.js.map")(path)))).toBe(true) + expect([read(join(dir, "a.js")), read(join(dir, "a.js.map"))]).toEqual([code, original]) + await run(injectDirectory(dir, { dryRun: false })) + expect(mappings()).toBe(";AAAA;AACA") + }) + + test("repairs a registered file whose map lacks its id, moving the map once", async () => { + const id = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + writeFileSync(join(dir, "r.js"), `${debugIdSnippet(id)}\nr()\n//# debugId=${id}\n`) + writeFileSync(join(dir, "r.js.map"), map("r.js", { mappings: "AAAA" })) + + const [result] = await run(injectDirectory(dir, { dryRun: false })) + const repaired = JSON.parse(read(join(dir, "r.js.map"))) + expect([result?.status, result?.mapUpdated, repaired.mappings, repaired.debugId]).toEqual([ + "already_injected", + true, + ";AAAA", + id, + ]) + await run(injectDirectory(dir, { dryRun: false })) + expect(JSON.parse(read(join(dir, "r.js.map"))).mappings).toBe(";AAAA") + }) + + test("gives identical JS with different maps different ids", async () => { + mkdirSync(join(dir, "r1")) + mkdirSync(join(dir, "r2")) + const code = "throwIt()\n" + writeFileSync(join(dir, "r1/a.js"), code) + writeFileSync(join(dir, "r1/a.js.map"), map("a.js", { mappings: "AAAA" })) + writeFileSync(join(dir, "r2/a.js"), code) + writeFileSync(join(dir, "r2/a.js.map"), map("a.js", { mappings: "AACA" })) + + const [first] = await run(injectDirectory(join(dir, "r1"), { dryRun: false })) + const [second] = await run(injectDirectory(join(dir, "r2"), { dryRun: false })) + expect(Option.getOrNull(first?.debugId ?? Option.none())).not.toBe( + Option.getOrNull(second?.debugId ?? Option.none()), + ) + }) + + test("never writes an id into a map two files share, and uploads it once per file", async () => { + mkdirSync(join(dir, "maps")) + writeFileSync(join(dir, "app.js"), "a()\n//# sourceMappingURL=maps/app.map\n") + writeFileSync(join(dir, "app-legacy.js"), "b()\n//# sourceMappingURL=maps/app.map\n") + writeFileSync(join(dir, "maps/app.map"), map("app.js")) + + const results = await run(injectDirectory(dir, { dryRun: false })) + expect(read(join(dir, "maps/app.map"))).toBe(map("app.js")) + const ids = Arr.map(results, (r) => Option.getOrNull(r.debugId)) + expect(ids[0]).not.toBe(ids[1]) + // The lines did not move: the snippet went after the code. + expect(Str.startsWith("b()\n")(read(join(dir, "app-legacy.js")))).toBe(true) + + const seen: Array = [] + const server = Bun.serve({ + port: 0, + fetch: (request) => { + seen.push(new URL(request.url).searchParams) + return Response.json({ id: "smap_1" }) + }, + }) + const outcomes = await Effect.runPromise( + uploadDirectory( + dir, + { + apiUrl: `http://127.0.0.1:${server.port}`, + token: "t", + service: Option.none(), + version: Option.none(), + urlPrefix: Option.none(), + concurrency: 1, + }, + () => Effect.void, + ).pipe(Effect.provide(Layer.merge(FetchHttpClient.layer, BunServices.layer))), + ) + await server.stop(true) + expect(Arr.map(outcomes, (o) => o._tag)).toEqual(["uploaded", "uploaded"]) + // Each file is uploaded under its own path with the id its own snippet registers. + expect(Arr.map(seen, (params) => [params.get("minified_path"), params.get("debug_id")])).toEqual( + Arr.map(results, (r) => [r.file, Option.getOrNull(r.debugId)]), + ) + }) + + test("refuses a map outside the build directory, by path or by symlink", async () => { + const build = join(dir, "dist") + mkdirSync(build) + const outside = join(dir, "secret.json") + writeFileSync(outside, JSON.stringify({ version: 3, sources: ["x"], mappings: "AAAA" })) + writeFileSync(join(build, "up.js"), "u()\n//# sourceMappingURL=../secret.json\n") + writeFileSync(join(build, "abs.js"), `v()\n//# sourceMappingURL=${outside}\n`) + writeFileSync(join(build, "link.js"), "w()\n") + symlinkSync(outside, join(build, "link.js.map")) + writeFileSync(join(build, "pkg.js"), "p()\n") + writeFileSync(join(build, "pkg.js.map"), JSON.stringify({ name: "not-a-map" })) + + const results = await run(injectDirectory(build, { dryRun: false })) + + expect(Arr.map(results, (r) => [r.file, r.status])).toEqual([ + ["abs.js", "unsafe_map"], + ["link.js", "unsafe_map"], + ["pkg.js", "invalid_map"], + ["up.js", "unsafe_map"], + ]) + expect(read(outside)).toBe(JSON.stringify({ version: 3, sources: ["x"], mappings: "AAAA" })) + expect(read(join(build, "pkg.js.map"))).toBe(JSON.stringify({ name: "not-a-map" })) + expect(read(join(build, "up.js"))).toBe("u()\n//# sourceMappingURL=../secret.json\n") + }) + + test("keeps an existing registered debug id and is a no-op on a second run", async () => { + const existing = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + const injected = `y()\n${debugIdSnippet(existing)}\n//# debugId=${existing}\n//# sourceMappingURL=y.js.map\n` + writeFileSync(join(dir, "y.js"), injected) + writeFileSync(join(dir, "y.js.map"), map("y.js")) + writeFileSync(join(dir, "z.js"), "z()\n") + writeFileSync(join(dir, "z.js.map"), map("z.js")) + + const first = await run(injectDirectory(dir, { dryRun: false })) + expect(read(join(dir, "y.js"))).toBe(injected) + expect(JSON.parse(read(join(dir, "y.js.map"))).debug_id).toBe(existing) + expect(Arr.map(first, (r) => r.status)).toEqual(["already_injected", "injected"]) + + const zAfterFirst = read(join(dir, "z.js")) + const zMapAfterFirst = read(join(dir, "z.js.map")) + const second = await run(injectDirectory(dir, { dryRun: false })) + expect(Arr.map(second, (r) => [r.status, r.mapUpdated])).toEqual([ + ["already_injected", false], + ["already_injected", false], + ]) + expect(read(join(dir, "z.js"))).toBe(zAfterFirst) + expect(read(join(dir, "z.js.map"))).toBe(zMapAfterFirst) + expect(existingDebugId(zAfterFirst)).toEqual(Option.some(debugIdFor("z()\n", map("z.js")))) + }) + + test("keeps the id a runtime registration carries without a comment", async () => { + const existing = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + const registered = `${debugIdSnippet(existing)}\nr()\n` + writeFileSync(join(dir, "r.js"), registered) + writeFileSync(join(dir, "r.js.map"), map("r.js")) + + const [result] = await run(injectDirectory(dir, { dryRun: false })) + + expect(Option.getOrNull(result?.debugId ?? Option.none())).toBe(existing) + expect(read(join(dir, "r.js"))).toBe(registered) + expect(JSON.parse(read(join(dir, "r.js.map"))).debugId).toBe(existing) + }) + + test("registers a bundler's bare debugId comment at runtime, reusing its id", async () => { + const existing = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + // Rollup/Vite `sourcemapDebugIds` output: the comment, nothing that runs. + const v = `v()\n//# debugId=${existing}\n//# sourceMappingURL=v.js.map\n` + writeFileSync(join(dir, "v.js"), v) + writeFileSync(join(dir, "v.js.map"), map("v.js")) + writeFileSync(join(dir, "w.js"), `w()\n//# debugId=${existing}\n//# sourceMappingURL=w.js.map\n`) + writeFileSync(join(dir, "w.js.map"), map("w.js", { debugId: existing })) + + const results = await run(injectDirectory(dir, { dryRun: false })) + + expect(read(join(dir, "v.js"))).toBe(`${debugIdSnippet(existing)}\n${v}`) + const vMap = JSON.parse(read(join(dir, "v.js.map"))) + expect([vMap.debugId, vMap.debug_id, vMap.mappings]).toEqual([existing, existing, ";AAAA,SAAS;AACT"]) + expect(Arr.map(results, (r) => [r.file, r.status, Option.getOrNull(r.debugId)])).toEqual([ + ["v.js", "injected", existing], + ["w.js", "injected", existing], + ]) + expect(JSON.parse(read(join(dir, "w.js.map"))).debug_id).toBe(existing) + + const again = await run(injectDirectory(dir, { dryRun: false })) + expect(Arr.map(again, (r) => [r.status, r.mapUpdated])).toEqual([ + ["already_injected", false], + ["already_injected", false], + ]) + expect(JSON.parse(read(join(dir, "v.js.map"))).mappings).toBe(";AAAA,SAAS;AACT") + }) + + test("does not take a bundled SDK reading the debug id map for this file's registration", async () => { + const existing = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + const sdk = "var o=owner._mapleDebugIds||owner._sentryDebugIds;o&&(ids[o[k]]=k);" + const code = `${sdk}\n//# debugId=${existing}\n//# sourceMappingURL=sdk.js.map\n` + writeFileSync(join(dir, "sdk.js"), code) + writeFileSync(join(dir, "sdk.js.map"), map("sdk.js")) + + const [result] = await run(injectDirectory(dir, { dryRun: false })) + + expect(result?.status).toBe("injected") + expect(read(join(dir, "sdk.js"))).toBe(`${debugIdSnippet(existing)}\n${code}`) + const [again] = await run(injectDirectory(dir, { dryRun: false })) + expect(again?.status).toBe("already_injected") + }) + + test("handles CRLF line endings and a missing trailing newline", async () => { + const crlf = "c()\r\n//# sourceMappingURL=c.js.map\r\n" + const noNewline = "d()\n//# sourceMappingURL=d.js.map" + const existing = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + const crlfBare = `e()\r\n//# debugId=${existing}\r\n//# sourceMappingURL=e.js.map` + writeFileSync(join(dir, "c.js"), crlf) + writeFileSync(join(dir, "c.js.map"), map("c.js")) + writeFileSync(join(dir, "d.js"), noNewline) + writeFileSync(join(dir, "d.js.map"), map("d.js")) + writeFileSync(join(dir, "e.js"), crlfBare) + writeFileSync(join(dir, "e.js.map"), map("e.js")) + + const results = await run(injectDirectory(dir, { dryRun: false })) + + const idC = debugIdFor(crlf, map("c.js")) + const idD = debugIdFor(noNewline, map("d.js")) + expect(read(join(dir, "c.js"))).toBe( + `${debugIdSnippet(idC)}\nc()\r\n//# debugId=${idC}\n//# sourceMappingURL=c.js.map\r\n`, + ) + expect(read(join(dir, "d.js"))).toBe( + `${debugIdSnippet(idD)}\nd()\n//# debugId=${idD}\n//# sourceMappingURL=d.js.map`, + ) + expect(read(join(dir, "e.js"))).toBe(`${debugIdSnippet(existing)}\n${crlfBare}`) + expect(Arr.map(results, (r) => Option.getOrNull(r.debugId))).toEqual([idC, idD, existing]) + }) + + test("--dry-run reports the change and writes nothing", async () => { + writeFileSync(join(dir, "a.js"), "a()\n") + writeFileSync(join(dir, "a.js.map"), map("a.js")) + + const [result] = await run(injectDirectory(dir, { dryRun: true })) + + expect(result?.status).toBe("injected") + expect(read(join(dir, "a.js"))).toBe("a()\n") + expect(read(join(dir, "a.js.map"))).toBe(map("a.js")) + }) +}) diff --git a/apps/cli/src/core/sourcemaps.ts b/apps/cli/src/core/sourcemaps.ts new file mode 100644 index 0000000000..9694389f44 --- /dev/null +++ b/apps/cli/src/core/sourcemaps.ts @@ -0,0 +1,7 @@ +// `maple sourcemaps inject|upload`: the inject core is shared with the Alchemy Vite plugin. +import { SOURCE_MAP_MAX_BYTES } from "@maple/domain/http" + +export * from "@maple/sourcemaps" + +/** Maps above this are refused by the server (the largest it can symbolicate with), so they are skipped before the upload. */ +export const MAX_MAP_BYTES = SOURCE_MAP_MAX_BYTES diff --git a/apps/web/source-maps-dir.ts b/apps/web/source-maps-dir.ts new file mode 100644 index 0000000000..ab38d2e2f4 --- /dev/null +++ b/apps/web/source-maps-dir.ts @@ -0,0 +1,2 @@ +/** Where the web build's client source maps go, relative to the repo root: outside the deployed assets. */ +export const WEB_SOURCE_MAPS_DIR = "apps/web/.maple/sourcemaps/client" diff --git a/apps/web/src/lab/entries/error-issue.ts b/apps/web/src/lab/entries/error-issue.ts index c2b86b50a9..3b432d4031 100644 --- a/apps/web/src/lab/entries/error-issue.ts +++ b/apps/web/src/lab/entries/error-issue.ts @@ -8,6 +8,7 @@ import { ErrorIssueVerificationsResponse, IssueEscalationAttemptsResponse, } from "@maple/domain/http" +import type { SymbolicatedStack } from "@maple/domain/errors/js-stack" import { encodePublicId, V2ErrorIssueDetail } from "@maple/domain/http/v2" import { Effect, Option, Result, Schema, Array as Arr, String as Str } from "effect" import { Command } from "foldkit" @@ -35,7 +36,8 @@ import { // with a regression, as a member or an analyst, who reads it and gets no triage control // (`?role=member|analyst&tab=overview|occurrences|activity|grouping`; `context=none` drops the samples' // release and user, for the table's setup prompt; `grouping=populated|long|empty|loading|error` picks -// what the Grouping tab's reads answer). API Commands are dropped; the page +// what the Grouping tab's reads answer; `stack=raw|resolved|partial|missing_map` picks the source map +// state of the newest stack trace). API Commands are dropped; the page // is sent the answers its reads would get. const context: PageContext = { @@ -155,6 +157,228 @@ const detailWithoutContext: typeof detail = { })), } +const MINIFIED_STACK = Arr.join( + [ + "TypeError: Cannot read properties of undefined (reading 'plan')", + " at Kc (https://app.acme.dev/assets/index-Bx81.js:1:48213)", + " at Object.renew (https://app.acme.dev/assets/index-Bx81.js:1:51877)", + " at Ln (https://app.acme.dev/assets/vendor-9d2c.js:2:10442)", + " at Pn (https://app.acme.dev/assets/vendor-9d2c.js:2:10661)", + " at Hn (https://app.acme.dev/assets/vendor-9d2c.js:2:11020)", + " at async Wd (https://app.acme.dev/assets/index-Bx81.js:1:60115)", + " at async https://app.acme.dev/assets/vendor-9d2c.js:2:30077", + ], + "\n", +) + +const rawLines = Arr.drop(Str.split(MINIFIED_STACK, "\n"), 1) + +/** A frame as the backend writes it; `raw` is the matching minified line. */ +const frame = ( + index: number, + fields: Readonly<{ + function: string | null + file: string + line: number + column: number + in_app: boolean + resolved: boolean + context?: Readonly<{ pre: ReadonlyArray; line: string; post: ReadonlyArray }> + }>, +) => ({ + raw: Str.trim(rawLines[index] ?? ""), + function: fields.function, + file: fields.file, + line: fields.line, + column: fields.column, + in_app: fields.in_app, + resolved: fields.resolved, + context: fields.context ?? null, +}) + +const resolvePlanContext = { + pre: [ + "export const resolvePlan = (account: Account, catalog: PlanCatalog): Plan => {", + '\tconst subscription = account.subscriptions.find((s) => s.status === "active")', + "\t// A trial account has no paid subscription yet.", + '\tconst tier = subscription?.tier ?? "trial"', + "", + ], + line: "\treturn catalog[tier].plan", + post: [ + "}", + "", + "export const planLimits = (plan: Plan) => ({", + "\tseats: plan.seats,", + "\tevents: plan.events,", + ], +} + +const renewContext = { + pre: [ + "\tasync renew(accountId: AccountId) {", + "\t\tconst account = await this.accounts.get(accountId)", + "\t\tconst catalog = await this.catalog.current()", + "", + "\t\t// The plan decides the renewal price.", + ], + line: "\t\tconst plan = resolvePlan(account, catalog)", + post: [ + "\t\treturn this.billing.charge(account, plan.price)", + "\t}", + "", + "\tasync cancel(accountId: AccountId) {", + "\t\tconst account = await this.accounts.get(accountId)", + ], +} + +const libraryFrames = [ + frame(2, { + function: "dispatch", + file: "node_modules/hono/dist/compose.js", + line: 30, + column: 17, + in_app: false, + resolved: true, + }), + frame(3, { + function: "Hono.fetch", + file: "node_modules/hono/dist/hono-base.js", + line: 188, + column: 23, + in_app: false, + resolved: true, + }), + frame(4, { + function: "handle", + file: "node_modules/hono/dist/adapter/handle.js", + line: 12, + column: 9, + in_app: false, + resolved: true, + }), +] + +const topFrames = [ + frame(0, { + function: "resolvePlan", + file: "src/billing/plan.ts", + line: 47, + column: 28, + in_app: true, + resolved: true, + context: resolvePlanContext, + }), + frame(1, { + function: "SubscriptionService.renew", + file: "src/billing/subscription-service.ts", + line: 118, + column: 19, + in_app: true, + resolved: true, + context: renewContext, + }), +] + +const handleRenewalFrame = frame(5, { + function: "handleRenewal", + file: "src/routes/renewals.ts", + line: 31, + column: 5, + in_app: true, + resolved: true, + context: { + pre: ["export const handleRenewal = async (c: Context) => {"], + line: '\tawait subscriptions.renew(c.req.param("id"))', + post: ["\treturn c.json({ ok: true })", "}"], + }, +}) + +const resolvedStack: SymbolicatedStack = { + status: "resolved", + frames: [ + ...topFrames, + ...libraryFrames, + handleRenewalFrame, + frame(6, { + function: null, + file: "node_modules/hono/dist/router.js", + line: 74, + column: 11, + in_app: false, + resolved: true, + }), + ], + missing: [], +} + +/** The app bundle has a map; the vendor bundle does not, so its frames stay minified. */ +const partialStack: SymbolicatedStack = { + status: "partial", + frames: [ + ...topFrames, + frame(2, { + function: "Ln", + file: "https://app.acme.dev/assets/vendor-9d2c.js", + line: 2, + column: 10442, + in_app: false, + resolved: false, + }), + frame(3, { + function: "Pn", + file: "https://app.acme.dev/assets/vendor-9d2c.js", + line: 2, + column: 10661, + in_app: false, + resolved: false, + }), + frame(4, { + function: "Hn", + file: "https://app.acme.dev/assets/vendor-9d2c.js", + line: 2, + column: 11020, + in_app: false, + resolved: false, + }), + handleRenewalFrame, + ], + missing: ["https://app.acme.dev/assets/vendor-9d2c.js"], +} + +const missingMapStack: SymbolicatedStack = { + status: "missing_map", + frames: Arr.map(rawLines, (raw) => ({ + raw: Str.trim(raw), + function: null, + file: null, + line: null, + column: null, + in_app: true, + resolved: false, + context: null, + })), + missing: ["https://app.acme.dev/assets/index-Bx81.js", "https://app.acme.dev/assets/vendor-9d2c.js"], +} + +/** The same issue as each source map state would answer it; `raw` is an API with no symbolicated stack. */ +const STACKS = ["raw", "resolved", "partial", "missing_map"] as const +type StackState = (typeof STACKS)[number] + +const withStack = (base: typeof detail, state: StackState): typeof detail => + state === "raw" + ? base + : Schema.decodeSync(V2ErrorIssueDetail)({ + ...Schema.encodeSync(V2ErrorIssueDetail)(base), + latest_stacktrace: MINIFIED_STACK, + latest_stack: + state === "resolved" + ? resolvedStack + : state === "partial" + ? partialStack + : missingMapStack, + }) + /** Reads, writes and the window resolve go to the API; the lab answers them itself. */ const isLocalCommand = (command: { readonly name: string }): boolean => !/^(Fetch|Run|Create|Link|Unlink|Comment|Evaluate|ResolveIssueWindow)/.test(command.name) @@ -177,6 +401,7 @@ const Flags = Schema.Struct({ tab: Schema.Literals(TABS), context: Schema.Literals(CONTEXTS), grouping: Schema.Literals(GROUPING_STATES), + stack: Schema.Literals(STACKS), }) type Flags = typeof Flags.Type type LabRole = Flags["role"] @@ -186,6 +411,7 @@ const decodeRole = Schema.decodeUnknownOption(Schema.Literals(ROLES)) const decodeTab = Schema.decodeUnknownOption(Schema.Literals(TABS)) const decodeContext = Schema.decodeUnknownOption(Schema.Literals(CONTEXTS)) const decodeGrouping = Schema.decodeUnknownOption(Schema.Literals(GROUPING_STATES)) +const decodeStack = Schema.decodeUnknownOption(Schema.Literals(STACKS)) const LAB_FAILURE = toLoadFailure("Maple couldn't query your telemetry.") @@ -224,7 +450,9 @@ const init = (flags: Flags) => { [ Message.CompletedFetchDetail({ key: keyOf("detail"), - result: Result.succeed(flags.context === "none" ? detailWithoutContext : detail), + result: Result.succeed( + withStack(flags.context === "none" ? detailWithoutContext : detail, flags.stack), + ), }), Message.CompletedFetchAffectedUsers({ key: keyOf("affectedUsers"), @@ -335,6 +563,7 @@ export const lab = defineShellLab("Error issue", { decodeGrouping(params.get("grouping")), (): GroupingState => "populated", ), + stack: Option.getOrElse(decodeStack(params.get("stack")), (): StackState => "raw"), } }), init, diff --git a/apps/web/src/lab/registry.ts b/apps/web/src/lab/registry.ts index 2bc1f182f7..57223d9c17 100644 --- a/apps/web/src/lab/registry.ts +++ b/apps/web/src/lab/registry.ts @@ -639,7 +639,7 @@ export const LAB_ENTRIES: ReadonlyArray = [ path: "/lab/error-issue", title: "Error issue", description: - "The error issue page over one surging, regressed high-severity TypeError: the occurrence chart and its tooltip, the Get it fixed panel, the stat rail and the rail. The Grouping tab shows every fingerprint rule and source, a pinned fingerprint, a long frame list and similar issues (?grouping=populated|long|empty|loading|error). As a member or an analyst, who reads it and gets no triage control (?role=member|analyst&tab=overview|occurrences|activity|grouping).", + "The error issue page over one surging, regressed high-severity TypeError: the occurrence chart and its tooltip, the Get it fixed panel, the stat rail and the rail. The Grouping tab shows every fingerprint rule and source, a pinned fingerprint, a long frame list and similar issues (?grouping=populated|long|empty|loading|error). The stack trace in each source map state (?stack=raw|resolved|partial|missing_map). As a member or an analyst, who reads it and gets no triage control (?role=member|analyst&tab=overview|occurrences|activity|grouping).", kind: "lab", session: "none", }, diff --git a/apps/web/src/page/errors/issue/message.ts b/apps/web/src/page/errors/issue/message.ts index 15df422e42..b24d841b79 100644 --- a/apps/web/src/page/errors/issue/message.ts +++ b/apps/web/src/page/errors/issue/message.ts @@ -76,6 +76,8 @@ export const Message = defineMessageUnion({ ClickedRetryGrouping: {}, ClickedRetrySimilar: {}, ToggledSkippedFrames: { fingerprintHash: Schema.String }, + ToggledStackRow: { key: Schema.String }, + ToggledRawStack: {}, ClickedSplitOut: { fingerprintHash: Schema.String }, CompletedSplitOut: { fingerprintHash: Schema.String, result: Schema.Result(Schema.Null, LoadFailure) }, ClickedMergeSimilar: { sourceIssueId: ErrorIssueId }, diff --git a/apps/web/src/page/errors/issue/model.ts b/apps/web/src/page/errors/issue/model.ts index 93f1bdd43b..d9c609304b 100644 --- a/apps/web/src/page/errors/issue/model.ts +++ b/apps/web/src/page/errors/issue/model.ts @@ -59,6 +59,10 @@ export const Model = Schema.Struct({ similar: keyed(ErrorIssueSimilarResponse), /** Fingerprints whose skipped frames are shown. */ openSkippedFrames: Schema.Array(Schema.String), + /** The stack trace's rows flipped from their default (the top app frame open, the rest closed). */ + stackToggles: Schema.Array(Schema.String), + /** The symbolicated stack is swapped for the raw text as the SDK sent it. */ + isShowingRawStack: Schema.Boolean, /** The fingerprint being split out, while its detach is in flight. */ splittingHash: Schema.NullOr(Schema.String), /** The similar issue being merged into this one, while the merge is in flight. */ diff --git a/apps/web/src/page/errors/issue/stack-trace.scene.test.ts b/apps/web/src/page/errors/issue/stack-trace.scene.test.ts new file mode 100644 index 0000000000..87db928b02 --- /dev/null +++ b/apps/web/src/page/errors/issue/stack-trace.scene.test.ts @@ -0,0 +1,231 @@ +import { OrgId } from "@maple/domain" +import type { SymbolicatedStack } from "@maple/domain/errors/js-stack" +import { ErrorIssueId } from "@maple/domain/http" +import { encodePublicId, V2ErrorIssueDetail } from "@maple/domain/http/v2" +import { Option, Result, Schema } from "effect" +import type { Html, HtmlBuilder } from "foldkit/html" +import { click, expect as expectView, given, role, scene, selector, text } from "foldkit/scene" +import { describe, expect, test } from "vitest" +import type { PageContext } from "../../contract" +import { detailOf } from "./derive" +import { Message } from "./message" +import type { Model } from "./model" +import { init, update } from "./update" +import { exceptionPanel } from "./view-overview" + +// The exception panel's stack: mapped frames when a source map matched, the raw text otherwise. + +const orgId = Schema.decodeSync(OrgId)("org_acme") +const issueId = Schema.decodeSync(ErrorIssueId)("0199a004-0000-7000-8000-000000000001") +const context: PageContext = { orgId, pinnedNamespace: null, timeZone: "UTC" } +const window = { startTime: "2026-10-01 00:00:00", endTime: "2026-10-01 12:00:00" } +const NOW = Date.UTC(2026, 9, 1, 12) +const pageUpdate = (model: Model, message: Message) => update(model, message, context) + +const RAW = "TypeError: x is undefined\n at Kc (https://app.acme.dev/assets/index-Bx81.js:1:48213)" + +const frame = ( + fields: Partial & { function: string }, +): SymbolicatedStack["frames"][number] => ({ + raw: `at ${fields.function}`, + file: "src/billing/plan.ts", + line: 10, + column: 3, + in_app: true, + resolved: true, + context: null, + ...fields, +}) + +const resolved: SymbolicatedStack = { + status: "resolved", + frames: [ + frame({ + function: "resolvePlan", + context: { pre: ["const tier = account.tier"], line: "return catalog[tier].plan", post: ["}"] }, + }), + frame({ function: "dispatch", file: "node_modules/hono/dist/compose.js", in_app: false }), + frame({ function: "handle", file: "node_modules/hono/dist/handle.js", in_app: false }), + frame({ + function: "handleRenewal", + file: "src/routes/renewals.ts", + context: { pre: [], line: "await subscriptions.renew(id)", post: [] }, + }), + ], + missing: [], +} + +const missingMap: SymbolicatedStack = { + status: "missing_map", + frames: [], + missing: ["https://app.acme.dev/assets/index-Bx81.js"], +} + +const wireWith = (stack: SymbolicatedStack | null, raw: string) => + Schema.decodeSync(V2ErrorIssueDetail)({ + id: encodePublicId("iss", issueId), + object: "error_issue", + kind: "error", + fingerprint_hash: "1", + service_name: "web", + exception_type: "TypeError", + exception_message: "x is undefined", + error_label: "TypeError", + top_frame: "at Kc (index-Bx81.js:1:48213)", + workflow_state: "triage", + priority: 1, + severity: null, + severity_source: null, + source_ref: null, + assigned_actor: null, + lease_holder: null, + lease_expires_at: null, + claimed_at: null, + notes: null, + first_seen_at: "2026-10-01T10:00:00.000Z", + last_seen_at: "2026-10-01T11:44:00.000Z", + occurrence_count: 12, + resolved_at: null, + last_resolved_at: null, + last_regressed_at: null, + regression_count: 0, + resolved_versions: [], + snooze_until: null, + archived_at: null, + has_open_incident: false, + comment_count: 0, + open_pull_request_count: 0, + merged_pull_request_count: 0, + timeseries: [], + sample_traces: [], + incidents: [], + environments: [], + latest_stacktrace: raw, + latest_stack: stack, + }) + +const delivered = (model: Model, stack: SymbolicatedStack | null, raw: string): Model => + pageUpdate( + model, + Message.CompletedFetchDetail({ + key: model.detail.key ?? "", + result: Result.succeed(wireWith(stack, raw)), + }), + ).model + +const loadedWith = (stack: SymbolicatedStack | null, raw: string = RAW): Model => + delivered( + pageUpdate( + init({ issueId, search: {} }, context).model, + Message.CompletedResolveWindow({ window, nowMs: NOW, mode: "Load" }), + ).model, + stack, + raw, + ) + +const view = (model: Model, h: HtmlBuilder): Html => + Option.match(detailOf(model), { + onNone: () => h.div([], []), + onSome: (detail) => + exceptionPanel(h, model, detail.issue, detail.latestStacktrace, detail.latestStack), + }) + +describe("issue stack trace", () => { + test("a mapped stack opens on the top app frame's code, with library frames folded", () => { + scene( + { update: pageUpdate, view }, + given(loadedWith(resolved)), + expectView(text("Source mapped")).toExist(), + expectView(selector("#issue-stack-frame-0 [data-error-line]")).toExist(), + expectView(text("dispatch")).toBeAbsent(), + click(role("button", { name: "2 library frames" })), + expectView(text("dispatch")).toExist(), + expectView(selector("#issue-stack-frame-3")).toBeAbsent(), + click(role("button", { name: /handleRenewal/ })), + expectView(selector("#issue-stack-frame-3 [data-error-line]")).toExist(), + ) + }) + + test("Raw swaps the frames for the text the SDK sent, and back", () => { + scene( + { update: pageUpdate, view }, + given(loadedWith(resolved)), + expectView(text(/assets\/index-Bx81\.js:1:48213/)).toBeAbsent(), + click(role("button", { name: "Raw" })), + expectView(text(/assets\/index-Bx81\.js:1:48213/)).toExist(), + expectView(text("resolvePlan")).toBeAbsent(), + click(role("button", { name: "Raw" })), + expectView(text("resolvePlan")).toExist(), + ) + }) + + test("a stack with no map keeps the raw text and names the file to upload a map for", () => { + scene( + { update: pageUpdate, view }, + given(loadedWith(missingMap)), + expectView( + text(/Could not map https:\/\/app\.acme\.dev\/assets\/index-Bx81\.js to source/), + ).toExist(), + expectView(text("maple sourcemaps upload")).toExist(), + expectView(text("Full stack trace")).toExist(), + expectView(text("Source mapped")).toBeAbsent(), + ) + }) + + test("a partly mapped stack lists the files that did not map, in the page rather than a tooltip", () => { + const partial: SymbolicatedStack = { + ...resolved, + status: "partial", + missing: ["https://app.acme.dev/assets/vendor-9f.js"], + } + scene( + { update: pageUpdate, view }, + given(loadedWith(partial)), + expectView(text("Partly source mapped")).toExist(), + expectView(text("Not mapped to source: https://app.acme.dev/assets/vendor-9f.js")).toExist(), + ) + }) + + test("Raised at keeps the reported frame when the top app frame did not map", () => { + const topUnmapped: SymbolicatedStack = { + ...resolved, + status: "partial", + frames: [ + frame({ function: "Kc", file: "https://app.acme.dev/assets/index-Bx81.js", resolved: false }), + ...resolved.frames, + ], + missing: ["https://app.acme.dev/assets/index-Bx81.js"], + } + scene( + { update: pageUpdate, view }, + given(loadedWith(topUnmapped)), + expectView(text("at Kc (index-Bx81.js:1:48213)")).toExist(), + expectView(text(/resolvePlan \(src\/billing\/plan\.ts/)).toBeAbsent(), + ) + }) + + test("a different stack arriving resets the rows the reader flipped", () => { + const flipped = pageUpdate(loadedWith(resolved), Message.ToggledStackRow({ key: "frame-3" })).model + const raw = pageUpdate(flipped, Message.ToggledRawStack()).model + const same = delivered(raw, resolved, RAW) + const next = delivered( + raw, + resolved, + `${RAW}\n at Zt (https://app.acme.dev/assets/index-Qz07.js:1:9)`, + ) + expect([same.stackToggles, same.isShowingRawStack]).toEqual([["frame-3"], true]) + expect([next.stackToggles, next.isShowingRawStack]).toEqual([[], false]) + const remapped = delivered(raw, { ...resolved, status: "partial" }, RAW) + expect([remapped.stackToggles, remapped.isShowingRawStack]).toEqual([[], false]) + }) + + test("an API with no symbolicated stack shows the raw disclosure as before", () => { + scene( + { update: pageUpdate, view }, + given(loadedWith(null)), + expectView(text("Full stack trace")).toExist(), + expectView(text(/Could not map/)).toBeAbsent(), + expectView(role("button", { name: "Raw" })).toBeAbsent(), + ) + }) +}) diff --git a/apps/web/src/page/errors/issue/update.ts b/apps/web/src/page/errors/issue/update.ts index 0e6b45651b..4c84808e6c 100644 --- a/apps/web/src/page/errors/issue/update.ts +++ b/apps/web/src/page/errors/issue/update.ts @@ -2,7 +2,7 @@ import { keyed, runSteps, type Step as KitStep } from "../../kit/keyed-step" import { chartEnvHandlers } from "@maple/views/charts/chart-env" import type { RequestMode } from "@maple/views/data/keyed" import { type ErrorIssueId, ErrorIssuePullRequestId } from "@maple/domain/http" -import { Option, Result, Schema, String as Str } from "effect" +import { Array as Arr, Option, Result, Schema, String as Str } from "effect" import { formatWarehouseDateTime } from "@maple/query-engine" import { SETUP_CARD_ID } from "./model" import { AsyncData, Command } from "foldkit" @@ -256,6 +256,8 @@ export const init = ( grouping: Keyed.idle(), similar: Keyed.idle(), openSkippedFrames: [], + stackToggles: [], + isShowingRawStack: false, splittingHash: null, mergingIssueId: null, groupingError: null, @@ -420,6 +422,33 @@ const navigateSearch = (model: Model, search: Search): Return => ({ }), }) +/** The stack as sent and as mapped: a map uploaded since the last load changes the second alone. */ +const stackIdentityOf = (model: Model): string | null => + Option.match(detailOf(model), { + onNone: () => null, + onSome: (detail) => + Arr.join( + [ + detail.latestStacktrace ?? "", + detail.latestStack?.status ?? "", + ...Arr.map( + detail.latestStack?.frames ?? [], + (frame) => + `${frame.function ?? ""}@${frame.file ?? ""}:${frame.line ?? ""}:${frame.column ?? ""}`, + ), + ], + "\n", + ), + }) + +/** The new detail; rows flipped open or closed belong to the old stack, so a different one resets them. */ +const withDetail = (model: Model, detail: Model["detail"]): Model => { + const next = { ...model, detail } + return stackIdentityOf(next) === stackIdentityOf(model) + ? next + : { ...next, stackToggles: [], isShowingRawStack: false } +} + export const update = (model: Model, message: Message, context: PageContext): Return => Message.match(message, { CompletedResolveWindow: ({ window, nowMs, mode }) => @@ -429,7 +458,7 @@ export const update = (model: Model, message: Message, context: PageContext): Re ]), CompletedFetchSession: (answer) => ({ model: acceptGrants(model, context.orgId, answer) }), CompletedFetchDetail: ({ key, result }) => - runSteps(syncSelects({ ...model, detail: Keyed.accept(model.detail, key, result) }), [ + runSteps(syncSelects(withDetail(model, Keyed.accept(model.detail, key, result))), [ loadedReads(context), vcsStep(context), groupingReads(context, "Load"), @@ -476,6 +505,15 @@ export const update = (model: Model, message: Message, context: PageContext): Re ClickedRetryGrouping: () => retryGrouping(model, context, "grouping"), ClickedRetrySimilar: () => retryGrouping(model, context, "similar"), ToggledSkippedFrames: ({ fingerprintHash }) => toggledSkippedFrames(model, fingerprintHash), + ToggledStackRow: ({ key }) => ({ + model: { + ...model, + stackToggles: model.stackToggles.includes(key) + ? Arr.filter(model.stackToggles, (toggled) => toggled !== key) + : [...model.stackToggles, key], + }, + }), + ToggledRawStack: () => ({ model: { ...model, isShowingRawStack: !model.isShowingRawStack } }), ClickedSplitOut: ({ fingerprintHash }) => clickedSplitOut(model, fingerprintHash), CompletedSplitOut: ({ fingerprintHash, result }) => completedGroupingWrite( diff --git a/apps/web/src/page/errors/issue/view-overview.ts b/apps/web/src/page/errors/issue/view-overview.ts index f13441e1a3..08701d66b6 100644 --- a/apps/web/src/page/errors/issue/view-overview.ts +++ b/apps/web/src/page/errors/issue/view-overview.ts @@ -13,9 +13,15 @@ import { Message } from "./message" import type { Model } from "./model" import { typography } from "@maple/views/ui/typography" import { hstack, vstack } from "@maple/views/ui/stack" -import { Array as Arr, String as Str } from "effect" +import { Array as Arr, Option, String as Str } from "effect" import { stripClass } from "@maple/views/ui/rule" -import { disclosureStrip } from "../../kit/disclosure-strip" +import { disclosureStrip, monospaceBlock } from "../../kit/disclosure-strip" +import type { SymbolicatedStack } from "@maple/domain/errors/js-stack" +import { badge } from "@maple/views/ui/display" +import { icon } from "@maple/views/ui/icon" +import { inlineCode } from "@maple/views/ui/inline-code" +import { stackFrameList } from "@maple/views/ui/stack-frames" +import { toggle } from "@maple/views/ui/toggle" // `IssueExceptionPanel` and `IssueStats`: what broke, then how often and since when. @@ -38,14 +44,26 @@ export const issueField = (h: H, label: string, children: ReadonlyArray): const COPY_CLASS = "-my-0.5 shrink-0 opacity-0 transition-opacity focus-visible:opacity-100 group-hover/mono:opacity-100 pointer-coarse:opacity-100" +/** The top in-app frame as `function (file:line:column)`, when a map resolved that frame itself. */ +const mappedTopFrame = (stack: SymbolicatedStack | null): string | undefined => { + if (stack === null) return undefined + const frame = Option.getOrUndefined(Arr.findFirst(stack.frames, (f) => f.in_app)) + if (frame === undefined || !frame.resolved || frame.file === null) return undefined + const position = + frame.line === null ? "" : `:${frame.line}${frame.column === null ? "" : `:${frame.column}`}` + return `${frame.function ?? ""} (${frame.file}${position})` +} + /** The exception message, the top frame it was raised from, and the newest full stack trace. */ export const exceptionPanel = ( h: H, model: Model, issue: ErrorIssueDocument, stacktrace: string | null, + stack: SymbolicatedStack | null, ): Html => { const message = stripAnsi(issue.exceptionMessage || issue.errorLabel) + const topFrame = mappedTopFrame(stack) ?? issue.topFrame return panel(h, { className: "shrink-0 overflow-hidden" }, [ panelHeader(h, { title: "What broke", @@ -64,7 +82,7 @@ export const exceptionPanel = ( "This error carries no message, only its type and where it was raised.", ]), issueField(h, "Raised at", [ - issue.topFrame + topFrame ? hstack(h, { gap: "1.5", align: "start", shrink: true, className: "group/mono" }, [ h.code( [ @@ -72,11 +90,11 @@ export const exceptionPanel = ( "min-w-0 break-words font-mono text-xs leading-5 text-foreground-soft", ), ], - breakablePath(h, issue.topFrame), + breakablePath(h, topFrame), ), CopyButton.view(h, { model: model.fingerprintCopy, - value: issue.topFrame, + value: topFrame, label: "top frame", toParentMessage: (message) => Message.GotFingerprintCopyMessage({ message }), className: COPY_CLASS, @@ -86,13 +104,106 @@ export const exceptionPanel = ( "No stack frame was attributed to this fingerprint", ]), ]), + ...missingMapHint(h, stack), ]), - ...(stacktrace === null - ? [] - : [disclosureStrip(h, { label: "Full stack trace", text: stripAnsi(stacktrace) })]), + ...stackFoot(h, model, stacktrace, stack), ]) } +const rawStrip = (h: H, stacktrace: string | null): ReadonlyArray => + stacktrace === null + ? [] + : [disclosureStrip(h, { label: "Full stack trace", text: stripAnsi(stacktrace) })] + +/** Where to start when nothing mapped: the first minified file that did not map to source. */ +const missingMapHint = (h: H, stack: SymbolicatedStack | null): ReadonlyArray => { + const file = stack?.status === "missing_map" ? stack.missing[0] : undefined + return file === undefined + ? [] + : [ + typography(h, { size: "xs", tone: "muted", as: "p", className: "break-all" }, [ + `Could not map ${file} to source. Upload this build's maps with `, + inlineCode(h, {}, ["maple sourcemaps upload"]), + ", or check the uploaded map matches the build.", + ]), + ] +} + +/** The symbolicated frames under a "Source mapped" bar, with "Raw" swapping in the text as sent. */ +const symbolicatedStrip = (h: H, model: Model, stacktrace: string | null, stack: SymbolicatedStack): Html => + h.div( + [h.Class("border-t")], + [ + hstack(h, { gap: "2", justify: "between", className: "px-4 py-2" }, [ + hstack(h, { gap: "2", shrink: true }, [ + typography(h, { size: "xs", tone: "muted" }, ["Stack trace"]), + badge( + h, + { + variant: stack.status === "resolved" ? "ok" : "meta", + size: "sm", + }, + stack.status === "resolved" + ? [icon(h, "CircleCheckIcon", {}), "Source mapped"] + : ["Partly source mapped"], + ), + ]), + ...(stacktrace === null + ? [] + : [ + toggle( + h, + { + isPressed: model.isShowingRawStack, + onClick: Message.ToggledRawStack(), + size: "xs", + variant: "outline", + }, + ["Raw"], + ), + ]), + ]), + ...(stack.status === "partial" && stack.missing.length > 0 + ? [ + typography( + h, + { size: "xs", tone: "muted", as: "p", className: "break-all border-t px-4 py-2" }, + [`Not mapped to source: ${Arr.join(stack.missing, ", ")}`], + ), + ] + : []), + model.isShowingRawStack && stacktrace !== null + ? monospaceBlock(h, stripAnsi(stacktrace)) + : stackFrameList(h, { + frames: stack.frames, + toggled: model.stackToggles, + onToggle: (key) => Message.ToggledStackRow({ key }), + idPrefix: "issue-stack", + className: "border-t", + }), + ], + ) + +/** The panel's foot: mapped frames once a map matched, else today's raw strip. */ +const stackFoot = ( + h: H, + model: Model, + stacktrace: string | null, + stack: SymbolicatedStack | null, +): ReadonlyArray => { + if (stack === null) return rawStrip(h, stacktrace) + switch (stack.status) { + case "resolved": + case "partial": + return stack.frames.length === 0 + ? rawStrip(h, stacktrace) + : [symbolicatedStrip(h, model, stacktrace, stack)] + case "missing_map": + case "not_applicable": + return rawStrip(h, stacktrace) + } +} + /** The rail tone of a severity: high and critical read as critical, unset as neutral. */ const SEVERITY_STAT_TONE = { critical: "crit", diff --git a/apps/web/src/page/errors/issue/view.ts b/apps/web/src/page/errors/issue/view.ts index 192c5b8a76..dc2b62e452 100644 --- a/apps/web/src/page/errors/issue/view.ts +++ b/apps/web/src/page/errors/issue/view.ts @@ -234,7 +234,7 @@ const overview = ( ...relatedAnomaliesSection(h, relatedAnomaliesOf(model), clock), ] : [ - exceptionPanel(h, model, issue, detail.latestStacktrace), + exceptionPanel(h, model, issue, detail.latestStacktrace, detail.latestStack), // How often and since when, over the window's bars: one panel, read top to bottom. panel(h, { className: "shrink-0 overflow-hidden" }, [ issueStats(h, issue, statInputs, { isFlush: true }), diff --git a/apps/web/src/page/kit/disclosure-strip.ts b/apps/web/src/page/kit/disclosure-strip.ts index 427d60615f..3956405bec 100644 --- a/apps/web/src/page/kit/disclosure-strip.ts +++ b/apps/web/src/page/kit/disclosure-strip.ts @@ -28,13 +28,17 @@ export const disclosureStrip = ( options.label, ], ), - h.pre( - [ - h.Class( - "max-h-72 overflow-auto border-t bg-surface-sunken px-4 pt-3 pb-8 [mask-image:linear-gradient(to_bottom,black_80%,transparent)] font-mono text-xs leading-5 whitespace-pre-wrap break-words text-foreground-soft", - ), - ], - [options.text], + monospaceBlock(h, options.text), + ], + ) + +/** The strip's open block on its own: a capped, scrolling run of monospace text on the sunken wash. */ +export const monospaceBlock = (h: HtmlBuilder, text: string): Html => + h.pre( + [ + h.Class( + "max-h-72 overflow-auto border-t bg-surface-sunken px-4 pt-3 pb-8 [mask-image:linear-gradient(to_bottom,black_80%,transparent)] font-mono text-xs leading-5 whitespace-pre-wrap break-words text-foreground-soft", ), ], + [text], ) diff --git a/apps/web/src/platform/service-identity.ts b/apps/web/src/platform/service-identity.ts new file mode 100644 index 0000000000..cceace42a8 --- /dev/null +++ b/apps/web/src/platform/service-identity.ts @@ -0,0 +1,5 @@ +/** + * The `service.name` the dashboard's browser telemetry reports. The deploy uploads its source maps + * under the same name (`alchemy.run.ts`), so error stacks match them by service and release. + */ +export const WEB_SERVICE_NAME = "maple-web" diff --git a/apps/web/src/platform/telemetry.ts b/apps/web/src/platform/telemetry.ts index f89a591b89..a18d1deb49 100644 --- a/apps/web/src/platform/telemetry.ts +++ b/apps/web/src/platform/telemetry.ts @@ -1,6 +1,7 @@ import { MapleFoldkit } from "@maple-dev/effect-sdk/foldkit" import { ANTICIPATED_ERROR_IDENTIFIERS } from "@maple/domain/anticipated-errors" import { selfIngestUrl } from "./ingest-url" +import { WEB_SERVICE_NAME } from "./service-identity" import { Option } from "effect" import { fromString } from "foldkit/url" import { urlToAppRoute } from "../route" @@ -19,7 +20,7 @@ const routeName = (pathname: string): string => * `maple.web.app` names the frontend that sent it. */ const maple = MapleFoldkit.make({ - serviceName: "maple-web", + serviceName: WEB_SERVICE_NAME, endpoint: selfIngestUrl, ingestKey: import.meta.env.VITE_MAPLE_INGEST_KEY, // The stage's name (`production`, `pr-`, `development`); a preview build's MODE is `production` too. diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index b523992152..3a12c91910 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -6,6 +6,8 @@ import { defineConfig, loadEnv, type Plugin } from "vite" import { siblingUrl } from "../../packages/infra/src/dev-urls.ts" import { clerkJsUrl } from "../../packages/domain/src/clerk-js-url.ts" import { versionManifest } from "./vite-plugin-version-manifest.ts" +import { mapleSourceMaps } from "../../packages/alchemy-maple/src/Vite.ts" +import { WEB_SOURCE_MAPS_DIR } from "./source-maps-dir.ts" const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.String)) @@ -141,6 +143,9 @@ export default defineConfig(({ mode, command }) => { // `/version.json`, which open tabs poll to offer a reload after a deploy (shell/version.ts). versionManifest(process.env.VITE_COMMIT_SHA?.trim() || ""), earlyBoot(), + // Hidden maps with debug ids, moved out of the served client into `.maple/` for the + // deploy to upload (`alchemy.run.ts`). Build only. + mapleSourceMaps({ mapsDir: path.resolve(import.meta.dirname, "..", "..", WEB_SOURCE_MAPS_DIR) }), ...(Str.toLowerCase(process.env.VITE_MAPLE_AUTH_MODE?.trim()) === "clerk" && clerkKey ? [clerkEarlyLoad(clerkKey)] : []), diff --git a/bun.lock b/bun.lock index f408ff9cea..0e337c68ea 100644 --- a/bun.lock +++ b/bun.lock @@ -170,6 +170,7 @@ "@maple/local-server": "workspace:*", "@maple/promql": "workspace:*", "@maple/query-engine": "workspace:*", + "@maple/sourcemaps": "workspace:*", "effect": "catalog:effect", }, "devDependencies": { @@ -615,24 +616,32 @@ "devDependencies": { "@alchemy.run/test": "catalog:alchemy", "@effect/platform-bun": "catalog:effect", + "@effect/platform-node": "catalog:effect", "@effect/vitest": "catalog:effect", + "@jridgewell/trace-mapping": "0.3.31", "@maple/domain": "workspace:*", "@maple/local-server": "workspace:*", + "@maple/sourcemaps": "workspace:*", "@types/bun": "^1.4.5", "@types/node": "catalog:tooling", "alchemy": "catalog:alchemy", "effect": "catalog:effect", "tsdown": "^0.23.7", "typescript": "catalog:tooling", + "vite": "catalog:", "vitest": "catalog:", }, "peerDependencies": { "@effect/platform-bun": "^4.0.0", + "@effect/platform-node": "^4.0.0", "alchemy": ">=2.0.0-beta.80 <3", "effect": "^4.0.0", + "vite": ">=6.0.0", }, "optionalPeers": [ "@effect/platform-bun", + "@effect/platform-node", + "vite", ], }, "packages/alerting-core": { @@ -834,6 +843,7 @@ "@maple/primitives": "workspace:*", "@maple/query-model": "workspace:*", "@maple/security-audit": "workspace:*", + "@maple/sourcemaps": "workspace:*", "@maple/strings": "workspace:*", "@maple/widgets": "workspace:*", "effect": "catalog:effect", @@ -1034,6 +1044,16 @@ "vitest": "catalog:", }, }, + "packages/sourcemaps": { + "name": "@maple/sourcemaps", + "dependencies": { + "effect": "catalog:effect", + }, + "devDependencies": { + "@types/node": "catalog:tooling", + "typescript": "catalog:tooling", + }, + }, "packages/status-page": { "name": "@maple/status-page", "dependencies": { @@ -1637,6 +1657,8 @@ "@maple/security-audit": ["@maple/security-audit@workspace:packages/security-audit"], + "@maple/sourcemaps": ["@maple/sourcemaps@workspace:packages/sourcemaps"], + "@maple/status": ["@maple/status@workspace:apps/status"], "@maple/status-page": ["@maple/status-page@workspace:packages/status-page"], diff --git a/packages/alchemy-maple/README.md b/packages/alchemy-maple/README.md index 7590507c8b..e1d17f8644 100644 --- a/packages/alchemy-maple/README.md +++ b/packages/alchemy-maple/README.md @@ -113,6 +113,7 @@ seam when constructing the API client without the Alchemy provider collection. | `Maple.UptimeMonitor` | Create / update / delete. Props are the `POST /v2/uptime_monitors` body; the kind is `config.type`, and changing it replaces the monitor. Outputs `monitorId`, `heartbeatUrl`. | | `Maple.StatusPage` | Create / update / delete through the page's config document, plus `password` and `custom_domain`. Components keep their IDs by name; an unset `manual_status` leaves a responder's override alone. Outputs `statusPageId`, `components`, `customDomain.dnsRecords`. | | `Maple.IngestKeys` | Read-only per-org singleton. Surfaces `publicKey` / `privateKey` as `Redacted` outputs; delete only stops tracking it. | +| `Maple.SourceMaps` | Uploads a build's JavaScript source maps (see below). Re-uploads only when the maps, service, release or prefix changed. Deleting it deletes nothing: older releases still need their maps, and Maple removes maps unused for 90 days. Needs `source_maps:write`. | ## Typed dashboard data @@ -203,6 +204,46 @@ Cloudflare options, forwarded unchanged. Full docs: [maple.dev/docs/iac/alchemy](https://maple.dev/docs/iac/alchemy). +## Source maps + +`@maple-dev/alchemy/vite` gives each built JS file a debug id and moves its source maps out of the +deployed output (`.maple/sourcemaps/` by default), so they are never served. `Maple.SourceMaps` +uploads them after the build, so error stacks in Maple show your original source. + +```typescript +// vite.config.ts +import { mapleSourceMaps } from "@maple-dev/alchemy/vite" + +export default defineConfig({ plugins: [mapleSourceMaps()] }) +``` + +```typescript +// alchemy.run.ts +Effect.gen(function* () { + const web = yield* Cloudflare.Website.Vite("web") + yield* Maple.SourceMaps("web-sourcemaps", { + dir: ".maple/sourcemaps/client", + service: "web", // the service.name the app reports + release: process.env.GITHUB_SHA, // its service.version: matches maps without a debug id + after: web.hash, // upload after the build, and re-check when it changes + matchBy: "release", // telemetry without debug ids: see below + }) +}) +``` + +Set `matchBy: "release"` when your telemetry reports no debug ids (Maple's SDKs other than +`@maple-dev/browser`): maps then upload without them, matched by `service`, `release` and path, so +a chunk two releases share keeps a map under each. The default, `"debugId"`, suits `@maple-dev/browser`. + +The first upload happens on the first deploy that runs the build after you add the plugin; a +redeploy that skips an unchanged build finds no maps and logs a warning. On that first deploy, a +chunk whose hashed name is unchanged gets new contents (the snippet goes in after Rollup names it), +so a browser or CDN that cached it may serve the old copy for that one release; later builds are +deterministic. + +The plugin runs in Node and needs `@effect/platform-node`. `dir` can also be any build output where +each JS file has its map beside it, as `maple sourcemaps upload` reads it. + ## Local development `Local` runs Maple Local inside `alchemy dev`: an embedded OTLP collector, query API and diff --git a/packages/alchemy-maple/package.json b/packages/alchemy-maple/package.json index 18911322c1..c8edef75ff 100644 --- a/packages/alchemy-maple/package.json +++ b/packages/alchemy-maple/package.json @@ -41,6 +41,10 @@ "./local-sidecar": { "types": "./dist/local-sidecar.d.mts", "import": "./dist/local-sidecar.mjs" + }, + "./vite": { + "types": "./dist/vite.d.mts", + "import": "./dist/vite.mjs" } }, "publishConfig": { @@ -58,25 +62,37 @@ "devDependencies": { "@alchemy.run/test": "catalog:alchemy", "@effect/platform-bun": "catalog:effect", + "@effect/platform-node": "catalog:effect", "@effect/vitest": "catalog:effect", + "@jridgewell/trace-mapping": "0.3.31", "@maple/domain": "workspace:*", "@maple/local-server": "workspace:*", + "@maple/sourcemaps": "workspace:*", "@types/bun": "^1.4.5", "@types/node": "catalog:tooling", "alchemy": "catalog:alchemy", "effect": "catalog:effect", "tsdown": "^0.23.7", "typescript": "catalog:tooling", + "vite": "catalog:", "vitest": "catalog:" }, "peerDependencies": { "@effect/platform-bun": "^4.0.0", + "@effect/platform-node": "^4.0.0", "alchemy": ">=2.0.0-beta.80 <3", - "effect": "^4.0.0" + "effect": "^4.0.0", + "vite": ">=6.0.0" }, "peerDependenciesMeta": { "@effect/platform-bun": { "optional": true + }, + "@effect/platform-node": { + "optional": true + }, + "vite": { + "optional": true } } } diff --git a/packages/alchemy-maple/src/MapleApi.ts b/packages/alchemy-maple/src/MapleApi.ts index ccffa44721..bc34cc620f 100644 --- a/packages/alchemy-maple/src/MapleApi.ts +++ b/packages/alchemy-maple/src/MapleApi.ts @@ -39,6 +39,12 @@ export interface MapleApiContract { readonly patch: (path: string, body: unknown) => Effect.Effect readonly put: (path: string, body: unknown) => Effect.Effect readonly delete: (path: string) => Effect.Effect + /** POSTs raw bytes (a file upload) as the body; `path` carries any query string. */ + readonly upload: ( + path: string, + body: Uint8Array, + contentType: string, + ) => Effect.Effect } export class MapleApi extends Context.Service()("Maple::Api") {} @@ -134,7 +140,12 @@ export const make = Effect.gen(function* () { const { baseUrl, apiKey } = yield* MapleEnvironment const httpClient = yield* HttpClient.HttpClient - const request = (method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE", path: string, body?: unknown) => { + const request = ( + method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE", + path: string, + body?: unknown, + raw?: { readonly bytes: Uint8Array; readonly contentType: string }, + ) => { const canAutomaticallyRetry = method === "GET" || method === "DELETE" const execute: (attempt: number) => Effect.Effect = Effect.fn( "MapleApi.requestAttempt", @@ -146,7 +157,9 @@ export const make = Effect.gen(function* () { Accept: "application/json", }), ) - if (body !== undefined) { + if (raw !== undefined) { + req = HttpClientRequest.bodyUint8Array(req, raw.bytes, raw.contentType) + } else if (body !== undefined) { req = yield* HttpClientRequest.bodyJson(req, body).pipe( Effect.mapError( (error) => @@ -212,6 +225,8 @@ export const make = Effect.gen(function* () { patch: (path: string, body: unknown) => request("PATCH", path, body), put: (path: string, body: unknown) => request("PUT", path, body), delete: (path: string) => request("DELETE", path), + upload: (path: string, bytes: Uint8Array, contentType: string) => + request("POST", path, undefined, { bytes, contentType }), } }) diff --git a/packages/alchemy-maple/src/Providers.ts b/packages/alchemy-maple/src/Providers.ts index 9a348016a0..96d3a1f309 100644 --- a/packages/alchemy-maple/src/Providers.ts +++ b/packages/alchemy-maple/src/Providers.ts @@ -8,6 +8,7 @@ import { Dashboard, DashboardProvider } from "./Dashboard" import { IngestKeys, IngestKeysProvider } from "./IngestKeys" import { MapleApiFromHttpClient } from "./MapleApi" import * as MapleEnvironment from "./MapleEnvironment" +import { SourceMaps, SourceMapsProvider } from "./SourceMaps" import { StatusPage, StatusPageProvider } from "./StatusPage" import { UptimeMonitor, UptimeMonitorProvider } from "./UptimeMonitor" @@ -25,7 +26,8 @@ export class Providers extends Provider.ProviderCollection()("Maple") * * Credentials come from `MAPLE_API_KEY` / `MAPLE_API_URL` and requests use the * runtime's global `fetch`. Use {@link providersWithDependencies} to supply a - * different environment or HTTP client. + * different environment or HTTP client. `Maple.SourceMaps` reads files through the stack's + * `FileSystem` and `Path`, which Alchemy supplies. */ export const providers = () => providersWithDependencies().pipe( @@ -59,6 +61,7 @@ export const providersWithDependencies = () => IngestKeys, UptimeMonitor, StatusPage, + SourceMaps, ]), ).pipe( Layer.provide( @@ -70,6 +73,7 @@ export const providersWithDependencies = () => IngestKeysProvider(), UptimeMonitorProvider(), StatusPageProvider(), + SourceMapsProvider(), ), ), Layer.provide(MapleApiFromHttpClient()), diff --git a/packages/alchemy-maple/src/SourceMaps.ts b/packages/alchemy-maple/src/SourceMaps.ts new file mode 100644 index 0000000000..011d1b5e7b --- /dev/null +++ b/packages/alchemy-maple/src/SourceMaps.ts @@ -0,0 +1,297 @@ +// BOUNDARY-FILE: This module reads source map files and a manifest from disk before upload. +import { createHash } from "node:crypto" +import { SOURCE_MAP_MAX_BYTES } from "@maple/sourcemaps/limits" +import { + existingDebugId, + findJsFiles, + isIndexMap, + MANIFEST_FILE, + mapDebugId, + mapUsers, + SourceMapsManifest, +} from "@maple/sourcemaps" +import { Array as Arr, Effect, Option, Order, Result, Schema, String as Str } from "effect" +import { FileSystem } from "effect/FileSystem" +import { Path } from "effect/Path" +import { isResolved } from "alchemy/Diff" +import * as Provider from "alchemy/Provider" +import { Resource } from "alchemy/Resource" +import { MapleSourceMapsReadError } from "./errors" +import { MapleApi } from "./MapleApi" +import type { Providers } from "./Providers" + +export interface SourceMapsProps { + /** + * The directory holding the maps: the Vite plugin's `mapsDir` (with its manifest), or any + * build output where each JS file has its map beside it. + */ + dir: string + /** The service the code reports as (OTel `service.name`). */ + service: string + /** + * The release it reports (OTel `service.version`). Maps without a debug id are matched by + * service, release and path, so they are skipped without one. + */ + release?: string + /** The path the files are served under, prepended to each file path, e.g. `static/`. */ + urlPrefix?: string + /** + * Any value from the build this follows, such as a Worker's asset hash: it orders the upload + * after the build and re-checks the maps when the build changes. Not uploaded. + */ + after?: unknown + /** + * How stacks find these maps. `"debugId"` (default) uploads each map under the debug id its file + * registers, for SDKs that report debug ids. `"release"` uploads without them, matched by service, + * release and path: for telemetry that sends no debug ids, where a chunk shared by two releases + * would otherwise keep one row under one release. Needs `release`. + */ + matchBy?: "debugId" | "release" +} + +export type SourceMaps = Resource< + "Maple.SourceMaps", + SourceMapsProps, + { + /** Maps uploaded by the last reconcile that found changed maps. */ + uploaded: number + /** The debug ids among them. */ + debugIds: ReadonlyArray + /** A digest of the maps and the props they were uploaded under; unchanged, nothing uploads. */ + digest: string + }, + never, + Providers +> + +/** + * Uploads a build's JavaScript source maps to Maple so error stacks show original source. Runs + * after the build, and uploads again only when the maps (or service, release or prefix) changed. + * Needs an API key with `source_maps:write`. + * + * Deleting it uploads nothing and deletes nothing on purpose: errors from earlier releases still + * need their maps, and the server deletes maps no stack has used for 90 days. + * + * @example + * ```typescript + * const web = yield* Cloudflare.Website.Vite("web") + * yield* Maple.SourceMaps("web-sourcemaps", { + * dir: ".maple/sourcemaps/client", + * service: "web", + * release: process.env.GITHUB_SHA, + * after: web.hash, + * }) + * ``` + */ +export const SourceMaps = Resource("Maple.SourceMaps") + +interface PlannedMap { + readonly minifiedPath: string + readonly debugId: Option.Option + readonly bytes: Uint8Array +} + +const decodeManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(SourceMapsManifest)) + +/** The served path of a file below the deploy root, `urlPrefix` first, never with a leading slash. */ +export const minifiedPathFor = (urlPrefix: string | undefined, file: string): string => { + const prefix = urlPrefix ?? "" + const joined = prefix === "" || Str.endsWith("/")(prefix) ? `${prefix}${file}` : `${prefix}/${file}` + return Str.replace(/^(?:~\/|\/)+/, "")(joined) +} + +const sha256 = (data: Uint8Array | string) => createHash("sha256").update(data).digest("hex") + +/** Every map in `props.dir` with the path and debug id it uploads under; none when the dir is absent. */ +const planMaps = (props: SourceMapsProps) => + Effect.gen(function* () { + const fs = yield* FileSystem + const path = yield* Path + const readError = (cause: unknown) => + new MapleSourceMapsReadError({ + message: `Could not read source maps in ${props.dir}`, + path: props.dir, + cause, + }) + if (!(yield* fs.exists(props.dir).pipe(Effect.mapError(readError)))) return [] + const manifestPath = path.join(props.dir, MANIFEST_FILE) + if (yield* fs.exists(manifestPath).pipe(Effect.mapError(readError))) { + const manifest = yield* fs + .readFileString(manifestPath) + .pipe(Effect.flatMap(decodeManifest), Effect.mapError(readError)) + return yield* Effect.forEach(manifest.files, (entry) => + Effect.mapBoth(fs.readFile(path.join(props.dir, entry.map)), { + onFailure: readError, + onSuccess: (bytes): PlannedMap => ({ + minifiedPath: minifiedPathFor(props.urlPrefix, entry.file), + debugId: Option.fromNullishOr(entry.debugId), + bytes, + }), + }), + ) + } + // No manifest: maps beside their JS files, as `maple sourcemaps upload` reads them. + const files = yield* findJsFiles(props.dir).pipe(Effect.mapError(readError)) + const users = mapUsers(files) + return yield* Effect.forEach( + Arr.flatMap(files, (js) => + Option.toArray(Option.map(js.mapPath, (mapPath) => ({ js, mapPath }))), + ), + ({ js, mapPath }) => + Effect.mapBoth(fs.readFile(mapPath), { + onFailure: readError, + onSuccess: (bytes): PlannedMap => { + const shared = (users.get(mapPath) ?? 0) > 1 + return { + minifiedPath: minifiedPathFor(props.urlPrefix, js.file), + // The file's own id; a shared map's id belongs to no one file. + debugId: Option.orElse(existingDebugId(js.code), () => + shared ? Option.none() : mapDebugId(new TextDecoder().decode(bytes)), + ), + bytes, + } + }, + }), + ) + }) + +/** Changes when any map, its path or debug id, or the props it uploads under change. */ +export const sourceMapsDigest = (props: SourceMapsProps, maps: ReadonlyArray): string => + sha256( + Arr.join( + [ + props.service, + props.release ?? "", + props.urlPrefix ?? "", + props.matchBy ?? "debugId", + ...Arr.map( + Arr.sort( + maps, + Order.mapInput(Order.String, (map: PlannedMap) => map.minifiedPath), + ), + (map) => + Arr.join( + [map.minifiedPath, Option.getOrElse(map.debugId, () => ""), sha256(map.bytes)], + "\u0001", + ), + ), + ], + "\u0000", + ), + ) + +const byRelease = (props: SourceMapsProps) => props.matchBy === "release" +const hasRelease = (props: SourceMapsProps) => props.release !== undefined && props.release !== "" + +/** Why a map is not uploaded, or none when it is. */ +const skipReason = (props: SourceMapsProps, map: PlannedMap): Option.Option => { + if (map.bytes.byteLength > SOURCE_MAP_MAX_BYTES) return Option.some("it is over 10 MiB") + if (isIndexMap(new TextDecoder().decode(map.bytes))) + return Option.some("index source maps are not supported") + if (byRelease(props) && !hasRelease(props)) return Option.some('`matchBy: "release"` needs a release') + if (Option.isNone(map.debugId) && !hasRelease(props)) + return Option.some("it has no debug id and no release is set") + return Option.none() +} + +const uploadQuery = (props: SourceMapsProps, map: PlannedMap): string => { + const params: Array<[string, string]> = [ + ["minified_path", map.minifiedPath], + ["service", props.service], + ] + if (!byRelease(props) && Option.isSome(map.debugId)) params.push(["debug_id", map.debugId.value]) + if (hasRelease(props)) params.push(["version", props.release ?? ""]) + return new URLSearchParams(params).toString() +} + +const MapJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)) +const decodeMapJson = Schema.decodeUnknownResult(MapJson) +const encodeMapJson = Schema.encodeResult(MapJson) + +/** + * The body to upload. Matched by release, the map's own `debugId` / `debug_id` go too, or the server + * would file it under that id and one release's upload would replace another's. + */ +const uploadBody = (props: SourceMapsProps, map: PlannedMap): Uint8Array => { + if (!byRelease(props)) return map.bytes + return Result.match( + Result.flatMap( + decodeMapJson(new TextDecoder().decode(map.bytes)), + ({ debugId: _a, debug_id: _b, ...rest }) => encodeMapJson(rest), + ), + { onFailure: () => map.bytes, onSuccess: (text) => new TextEncoder().encode(text) }, + ) +} + +export const SourceMapsProvider = () => + Provider.effect( + SourceMaps, + Effect.gen(function* () { + const api = yield* MapleApi + const platform = yield* Effect.context() + const plan = (props: SourceMapsProps) => + Effect.map(planMaps(props), (maps) => ({ maps, digest: sourceMapsDigest(props, maps) })).pipe( + Effect.provide(platform), + ) + // A redeploy of an unchanged build skips the bundler, so no maps were written this run. + const warnNoMaps = (props: SourceMapsProps) => + Effect.logWarning( + `No source maps in ${props.dir}: the build did not run in this deploy, so nothing was uploaded. The next deploy that builds uploads them.`, + ) + return { + // The maps on disk decide: a build that changed them updates, one that did not is a noop. + diff: Effect.fn(function* ({ news, output }) { + if (output === undefined || !isResolved(news)) return undefined + const planned = yield* plan(news) + if (planned.maps.length === 0) { + yield* warnNoMaps(news) + return { action: "noop" } as const + } + return planned.digest === output.digest + ? ({ action: "noop" } as const) + : ({ action: "update", stables: [] } as const) + }), + reconcile: Effect.fn(function* ({ news, output }) { + const planned = yield* plan(news) + // No maps here (a build that was skipped): keep what the last upload recorded. + if (planned.maps.length === 0) { + yield* warnNoMaps(news) + return output ?? { uploaded: 0, debugIds: [], digest: planned.digest } + } + if (output !== undefined && output.digest === planned.digest) return output + const sendable = yield* Effect.filter(planned.maps, (map) => + Option.match(skipReason(news, map), { + onNone: () => Effect.succeed(true), + onSome: (reason) => + Effect.as( + Effect.logWarning( + `Skipped the source map for ${map.minifiedPath}: ${reason}`, + ), + false, + ), + }), + ) + yield* Effect.forEach( + sendable, + (map) => + api.upload( + `/v2/source_maps?${uploadQuery(news, map)}`, + uploadBody(news, map), + "application/json", + ), + { concurrency: 4, discard: true }, + ) + yield* Effect.logInfo(`Uploaded ${sendable.length} source map(s) for ${news.service}`) + return { + uploaded: sendable.length, + debugIds: byRelease(news) + ? [] + : Arr.dedupe(Arr.getSomes(Arr.map(sendable, (map) => map.debugId))), + digest: planned.digest, + } + }), + // Earlier releases still need their maps; the server's retention removes unused ones. + delete: () => Effect.void, + } + }), + ) diff --git a/packages/alchemy-maple/src/Vite.ts b/packages/alchemy-maple/src/Vite.ts new file mode 100644 index 0000000000..2b8898031f --- /dev/null +++ b/packages/alchemy-maple/src/Vite.ts @@ -0,0 +1,113 @@ +/** + * `mapleSourceMaps()`: a Vite plugin that gives each built JS file a debug id, then moves its + * source maps out of the deployed output so they are never served. `Maple.SourceMaps` uploads + * them from there. + * + * @example + * ```typescript + * // vite.config.ts + * import { mapleSourceMaps } from "@maple-dev/alchemy/vite" + * + * export default defineConfig({ plugins: [mapleSourceMaps()] }) + * ``` + */ +import * as NodeServices from "@effect/platform-node/NodeServices" +import { injectDirectory, relocateMaps } from "@maple/sourcemaps" +import { Array as Arr } from "effect" +import * as Effect from "effect/Effect" +import { Path } from "effect/Path" +import type { Plugin } from "vite" + +export interface MapleSourceMapsOptions { + /** + * Where the maps go, outside the deployed output. Defaults to + * `/.maple/sourcemaps/`. + */ + readonly mapsDir?: string + /** + * The Vite environments whose output is processed. Defaults to `["client"]`: the browser + * bundle. A build without the environment API is always processed. + */ + readonly environments?: ReadonlyArray +} + +/** What one build did: the maps moved and the files the manifest lists. */ +export interface MapleSourceMapsResult { + readonly outDirs: ReadonlyArray + readonly mapsDir: string + readonly moved: number + readonly files: number +} + +/** Injects every output, then moves their maps to `mapsDir` under one manifest. */ +export const processBuildOutputs = (outDirs: ReadonlyArray, mapsDir: string) => + Effect.gen(function* () { + const outputs = yield* Effect.forEach(Arr.dedupe(outDirs), (outDir) => + Effect.map(injectDirectory(outDir, { dryRun: false }), (results) => ({ outDir, results })), + ) + const relocated = yield* relocateMaps(mapsDir, outputs) + return { + outDirs: Arr.map(outputs, (output) => output.outDir), + mapsDir, + moved: relocated.moved, + files: relocated.files.length, + } satisfies MapleSourceMapsResult + }) + +/** + * Requires source maps (`build.sourcemap` becomes `"hidden"` when unset or off, so no public + * `sourceMappingURL` comment is written). When a build finishes it injects debug ids into every + * output it wrote and moves each `.map` to `mapsDir` with a `maple-sourcemaps.json` manifest. Runs + * in Node; Bun is not required. + * + * The first deploy with the plugin changes chunk contents without changing their hashed names + * (the injection runs after Rollup names them), so a browser or CDN that cached a chunk from the + * build before may still serve it unshifted for that one release. Later builds are deterministic, + * so it does not recur. + */ +export const mapleSourceMaps = (options: MapleSourceMapsOptions = {}): Plugin => { + const environments = options.environments ?? ["client"] + let root = process.cwd() + // Output dirs written in the current build, per environment: several outputs may share a dir. + const written = new Map>() + // A build without the environment API (Vite 5) has no `environment` on its plugin context. + const environmentOf = (context: { readonly environment?: { readonly name: string } }) => + context.environment?.name + return { + name: "maple:source-maps", + apply: "build", + config: (config) => + config.build?.sourcemap === undefined || config.build.sourcemap === false + ? { build: { sourcemap: "hidden" } } + : undefined, + configResolved: (config) => { + root = config.root + }, + writeBundle(outputOptions) { + const environment = environmentOf(this) + if (environment !== undefined && !environments.includes(environment)) return + if (outputOptions.dir === undefined) return + const key = environment ?? "" + written.set(key, [...(written.get(key) ?? []), outputOptions.dir]) + }, + async closeBundle() { + const key = environmentOf(this) ?? "" + const dirs = written.get(key) ?? [] + written.delete(key) + if (dirs.length === 0) return + const program = Effect.gen(function* () { + const path = yield* Path + const outDirs = Arr.map(dirs, (dir) => path.resolve(root, dir)) + const mapsDir = + options.mapsDir === undefined + ? path.join(root, ".maple", "sourcemaps", path.basename(outDirs[0] ?? root)) + : path.resolve(root, options.mapsDir) + return yield* processBuildOutputs(outDirs, mapsDir) + }) + const result = await Effect.runPromise(program.pipe(Effect.provide(NodeServices.layer))) + this.info( + `moved ${result.moved} source map(s) to ${result.mapsDir}; ${result.files} file(s) carry a debug id`, + ) + }, + } +} diff --git a/packages/alchemy-maple/src/errors.ts b/packages/alchemy-maple/src/errors.ts index 59a1d13e53..56f1e43c05 100644 --- a/packages/alchemy-maple/src/errors.ts +++ b/packages/alchemy-maple/src/errors.ts @@ -128,6 +128,12 @@ export class MapleDashboardIdentityError extends Schema.TaggedError()( + "@maple/alchemy/errors/SourceMapsReadError", + { message: Schema.String, path: Schema.String, cause: Schema.Defect() }, +) {} + export type MapleClientError = | MapleApiRequestEncodingError | MapleApiTransportError diff --git a/packages/alchemy-maple/src/index.ts b/packages/alchemy-maple/src/index.ts index 182b7330c8..afc5c300cf 100644 --- a/packages/alchemy-maple/src/index.ts +++ b/packages/alchemy-maple/src/index.ts @@ -2,7 +2,7 @@ * Alchemy provider for Maple resources. * * Declare Maple API keys, ingest keys, dashboards, alert destinations, alert - * rules, uptime monitors and status pages in your `alchemy.run.ts`, authenticated with a `maple_ak_…` + * rules, uptime monitors, status pages and source map uploads in your `alchemy.run.ts`, authenticated with a `maple_ak_…` * API key against the Maple public v2 API. * * @example @@ -56,6 +56,7 @@ export { MapleAlertRuleOwnershipError, MapleAlertRuleTagsError, MapleDashboardIdentityError, + MapleSourceMapsReadError, MapleApiRequestEncodingError, MapleApiResponseDecodeError, MapleApiResponseReadError, @@ -75,6 +76,13 @@ export { IngestKeys, IngestKeysProvider, type IngestKeysProps } from "./IngestKe export { listAll, MapleApi, MapleApiFromHttpClient, MapleApiLive, type MapleApiContract } from "./MapleApi" export { DEFAULT_BASE_URL, fromEnv, MapleEnvironment } from "./MapleEnvironment" export { Providers, providers, providersWithDependencies } from "./Providers" +export { + minifiedPathFor, + SourceMaps, + SourceMapsProvider, + sourceMapsDigest, + type SourceMapsProps, +} from "./SourceMaps" export { StatusPage, StatusPageProvider, diff --git a/packages/alchemy-maple/test/engine.test.ts b/packages/alchemy-maple/test/engine.test.ts index 517d015b89..4dc4cd9040 100644 --- a/packages/alchemy-maple/test/engine.test.ts +++ b/packages/alchemy-maple/test/engine.test.ts @@ -120,6 +120,7 @@ const makeHarness = () => { else documents.delete(path) return Effect.void }), + upload: (path) => Effect.die(`unexpected upload ${path}`), } const providers = Layer.effect( Providers, diff --git a/packages/alchemy-maple/test/provider-layers.test.ts b/packages/alchemy-maple/test/provider-layers.test.ts index 5e634ce3a3..5a7a4c1fac 100644 --- a/packages/alchemy-maple/test/provider-layers.test.ts +++ b/packages/alchemy-maple/test/provider-layers.test.ts @@ -1,3 +1,4 @@ +import * as NodeServices from "@effect/platform-node/NodeServices" import { noopSession } from "alchemy/Report" import { ConfigProvider, Effect, Layer, Redacted, Record as Rec } from "effect" import { HttpClient, HttpClientResponse } from "effect/http" @@ -9,9 +10,11 @@ import { Providers, providers, providersWithDependencies } from "../src/Provider import { Stack } from "alchemy/Stack" import { Stage } from "alchemy/Stage" +// What Alchemy supplies a stack's providers: its identity and the platform's files and paths. const stackLayer = Layer.mergeAll( Layer.succeed(Stack, { name: "test", stage: "test", resources: {}, bindings: {}, actions: {} }), Layer.succeed(Stage, "test"), + NodeServices.layer, ) const session = noopSession @@ -115,6 +118,7 @@ describe("Maple provider layers", () => { "Maple.ApiKey", "Maple.Dashboard", "Maple.IngestKeys", + "Maple.SourceMaps", "Maple.StatusPage", "Maple.UptimeMonitor", ]) diff --git a/packages/alchemy-maple/test/providers.test.ts b/packages/alchemy-maple/test/providers.test.ts index 9dd8892919..1d3ed04832 100644 --- a/packages/alchemy-maple/test/providers.test.ts +++ b/packages/alchemy-maple/test/providers.test.ts @@ -41,6 +41,7 @@ const makeStub = ( patch: (path, body) => dispatch("PATCH", path, body), put: (path, body) => dispatch("PUT", path, body), delete: (path) => dispatch("DELETE", path), + upload: (path) => Effect.die(`unexpected upload ${path}`), }, } } diff --git a/packages/alchemy-maple/test/source-maps.test.ts b/packages/alchemy-maple/test/source-maps.test.ts new file mode 100644 index 0000000000..8d89a75a75 --- /dev/null +++ b/packages/alchemy-maple/test/source-maps.test.ts @@ -0,0 +1,219 @@ +import { describe, expect, it } from "@effect/vitest" +import * as NodeServices from "@effect/platform-node/NodeServices" +import * as Core from "@alchemy.run/test/Core" +import * as Provider from "alchemy/Provider" +import * as State from "alchemy/State" +import { Array as Arr, Effect, Layer, Option, Record as Rec, String as Str } from "effect" +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { MapleApi, type MapleApiContract } from "../src/MapleApi" +import { Providers } from "../src/Providers" +import { SourceMaps, SourceMapsProvider } from "../src/SourceMaps" +import { processBuildOutputs } from "../src/Vite" +import { SourceMapsManifest } from "@maple/sourcemaps" +import { Schema } from "effect" + +const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(SourceMapsManifest)) +const decodeMap = Schema.decodeUnknownSync( + Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)), +) + +interface Upload { + readonly path: string + readonly query: Readonly> + readonly body: string + readonly contentType: string +} + +const makeHarness = () => { + const uploads: Array = [] + const unexpected = (method: string) => (path: string) => Effect.die(`unexpected ${method} ${path}`) + const api: MapleApiContract = { + get: unexpected("GET"), + post: unexpected("POST"), + patch: unexpected("PATCH"), + put: unexpected("PUT"), + delete: unexpected("DELETE"), + upload: (path, body, contentType) => + Effect.sync(() => { + const url = new URL(path, "https://maple.test") + uploads.push({ + path: url.pathname, + query: Rec.fromEntries(Arr.fromIterable(url.searchParams)), + body: new TextDecoder().decode(body), + contentType, + }) + return { object: "source_map", id: `smap_${uploads.length}` } + }), + } + const providers = Layer.effect(Providers, Provider.collection([SourceMaps])).pipe( + Layer.provide(SourceMapsProvider()), + Layer.provide(Layer.succeed(MapleApi, api)), + Layer.provide(NodeServices.layer), + ) + const options = { providers, state: State.inMemoryState(), stage: "test", adopt: false, dev: false } + return { + uploads, + stack: (name: string) => Core.scratchStack(options, name), + run: (effect: Core.TestEffect) => Core.toEffect(effect, options), + } +} + +const map = (source: string) => + JSON.stringify({ version: 3, sources: [source], names: [], mappings: "AAAA;AACA" }) + +/** A built output with two JS files and their maps, processed as the Vite plugin does. */ +const buildOutput = (root: string, secondSource = "src/b.ts") => + Effect.gen(function* () { + const dist = join(root, "dist") + mkdirSync(join(dist, "assets"), { recursive: true }) + writeFileSync(join(dist, "assets/a.js"), "a()\n") + writeFileSync(join(dist, "assets/a.js.map"), map("src/a.ts")) + writeFileSync(join(dist, "assets/b.js"), "b()\n") + writeFileSync(join(dist, "assets/b.js.map"), map(secondSource)) + return yield* processBuildOutputs([dist], join(root, "maps")).pipe(Effect.provide(NodeServices.layer)) + }) + +describe("Maple.SourceMaps", () => { + it.live("uploads each map once, and again only when the build changed", () => { + const h = makeHarness() + const stack = h.stack("source-maps") + const root = mkdtempSync(join(tmpdir(), "maple-maps-")) + const props = { dir: join(root, "maps"), service: "web", release: "abc123", urlPrefix: "static/" } + return h.run( + Effect.gen(function* () { + yield* buildOutput(root) + const manifest = decodeManifest( + readFileSync(join(root, "maps/maple-sourcemaps.json"), "utf8"), + ) + const first = yield* stack.deploy(SourceMaps("maps", props)) + expect(first.uploaded).toBe(2) + expect( + Arr.map(h.uploads, (u) => [ + u.path, + u.query, + u.contentType, + u.body === + readFileSync( + join( + root, + "maps", + `${Str.replace("static/", "")(u.query["minified_path"] ?? "")}.map`, + ), + "utf8", + ), + ]), + ).toEqual( + Arr.map(manifest.files, (file) => [ + "/v2/source_maps", + { + minified_path: `static/${file.file}`, + service: "web", + debug_id: file.debugId, + version: "abc123", + }, + "application/json", + true, + ]), + ) + expect([...first.debugIds].sort()).toEqual( + Arr.map(manifest.files, (file) => file.debugId).sort(), + ) + + // Unchanged maps: a noop, nothing uploaded. + h.uploads.length = 0 + expect((yield* stack.plan(SourceMaps("maps", props))).resources.maps?.action).toBe("noop") + const second = yield* stack.deploy(SourceMaps("maps", props)) + expect([second.digest, h.uploads.length]).toEqual([first.digest, 0]) + + // A rebuild that changed a map uploads again. + yield* buildOutput(root, "src/b-changed.ts") + const third = yield* stack.deploy(SourceMaps("maps", props)) + expect(third.digest).not.toBe(first.digest) + expect(h.uploads.length).toBe(2) + + // Deleting uploads and deletes nothing: older releases still need their maps. + h.uploads.length = 0 + yield* stack.destroy() + expect(h.uploads).toEqual([]) + }), + ) + }) + + it.live("matched by release, uploads without debug ids, in the query or the map", () => { + const h = makeHarness() + const stack = h.stack("by-release") + const root = mkdtempSync(join(tmpdir(), "maple-maps-")) + const props = { dir: join(root, "maps"), service: "maple-web", release: "sha-1" } + return h.run( + Effect.gen(function* () { + yield* buildOutput(root) + const result = yield* stack.deploy( + SourceMaps("maps", { ...props, matchBy: "release" as const }), + ) + expect([result.uploaded, result.debugIds]).toEqual([2, []]) + expect(Arr.map(h.uploads, (u) => u.query)).toEqual([ + { minified_path: "assets/a.js", service: "maple-web", version: "sha-1" }, + { minified_path: "assets/b.js", service: "maple-web", version: "sha-1" }, + ]) + Arr.forEach(h.uploads, (u) => { + const body = decodeMap(u.body) + expect(["debugId" in body, "debug_id" in body, body["mappings"]]).toEqual([ + false, + false, + ";AAAA;AACA", + ]) + }) + // The default keeps the debug ids, so switching mode uploads again. + h.uploads.length = 0 + yield* stack.deploy(SourceMaps("maps", props)) + expect(Arr.every(h.uploads, (u) => u.query["debug_id"] !== undefined)).toBe(true) + expect(Arr.every(h.uploads, (u) => "debugId" in decodeMap(u.body))).toBe(true) + }), + ) + }) + + it.live("reads maps beside their JS without a manifest, skipping ones it cannot match", () => { + const h = makeHarness() + const stack = h.stack("plain-dir") + const root = mkdtempSync(join(tmpdir(), "maple-maps-")) + writeFileSync(join(root, "main.js"), "m()\n") + writeFileSync(join(root, "main.js.map"), map("src/main.ts")) + mkdirSync(join(root, "big")) + writeFileSync(join(root, "big/huge.js"), "h()\n") + writeFileSync( + join(root, "big/huge.js.map"), + `${Str.slice(0, -1)(map("src/huge.ts"))},"pad":"${Str.repeat(10 * 1024 * 1024)("x")}"}`, + ) + return h.run( + Effect.gen(function* () { + // No release and no debug id: nothing can match the map, so nothing goes up. + const without = yield* stack.deploy(SourceMaps("maps", { dir: root, service: "api" })) + expect([without.uploaded, h.uploads.length]).toEqual([0, 0]) + const withRelease = yield* stack.deploy( + SourceMaps("maps", { dir: root, service: "api", release: "v2" }), + ) + expect(withRelease.uploaded).toBe(1) + expect(Arr.map(h.uploads, (u) => u.query)).toEqual([ + { minified_path: "main.js", service: "api", version: "v2" }, + ]) + expect(Option.isNone(Option.fromNullishOr(h.uploads[0]?.query["debug_id"]))).toBe(true) + }), + ) + }) + + it.live("uploads nothing and keeps its record when the directory is gone", () => { + const h = makeHarness() + const stack = h.stack("missing-dir") + const root = mkdtempSync(join(tmpdir(), "maple-maps-")) + return h.run( + Effect.gen(function* () { + const result = yield* stack.deploy( + SourceMaps("maps", { dir: join(root, "never-built"), service: "web", release: "1" }), + ) + expect([result.uploaded, h.uploads.length]).toEqual([0, 0]) + }), + ) + }) +}) diff --git a/packages/alchemy-maple/test/status-page.test.ts b/packages/alchemy-maple/test/status-page.test.ts index 3bc679efdd..9023f6675d 100644 --- a/packages/alchemy-maple/test/status-page.test.ts +++ b/packages/alchemy-maple/test/status-page.test.ts @@ -173,6 +173,7 @@ const makeFake = () => { patch: (path, body) => Effect.suspend(() => route("PATCH", path, body)), put: (path, body) => Effect.suspend(() => route("PUT", path, body)), delete: (path) => Effect.suspend(() => route("DELETE", path)), + upload: (path) => Effect.die(`unexpected upload ${path}`), } return { api, diff --git a/packages/alchemy-maple/test/uptime-monitor.test.ts b/packages/alchemy-maple/test/uptime-monitor.test.ts index 85e49e8d79..8184a3219d 100644 --- a/packages/alchemy-maple/test/uptime-monitor.test.ts +++ b/packages/alchemy-maple/test/uptime-monitor.test.ts @@ -63,6 +63,7 @@ const makeFake = () => { calls.push({ method: "DELETE", path }) store.delete(path) }), + upload: (path) => Effect.die(`unexpected upload ${path}`), } return { api, calls, store } } diff --git a/packages/alchemy-maple/test/vite.test.ts b/packages/alchemy-maple/test/vite.test.ts new file mode 100644 index 0000000000..e7746cdf1f --- /dev/null +++ b/packages/alchemy-maple/test/vite.test.ts @@ -0,0 +1,158 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest" +import { originalPositionFor, TraceMap } from "@jridgewell/trace-mapping" +import { Array as Arr, Effect, Option, Order, Result, Schema, String as Str } from "effect" +import { SourceMapsManifest } from "@maple/sourcemaps" +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { build } from "vite" +import { mapleSourceMaps, processBuildOutputs } from "../src/Vite" +import * as NodeServices from "@effect/platform-node/NodeServices" + +const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(SourceMapsManifest)) + +const SOURCE = Arr.join( + [ + "export function thrower(x) {", + " if (x > 1) {", + ' throw new Error("boom-from-line-3")', + " }", + " return x", + "}", + "console.log(thrower(Math.random()))", + "", + ], + "\n", +) + +const walk = (dir: string): ReadonlyArray => + Arr.flatMap(readdirSync(dir, { withFileTypes: true }), (entry) => + entry.isDirectory() + ? Arr.map(walk(join(dir, entry.name)), (f) => `${entry.name}/${f}`) + : [entry.name], + ) + +let root = "" +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "maple-vite-")) + mkdirSync(join(root, "src")) + writeFileSync(join(root, "src/main.js"), SOURCE) +}) +afterEach(() => rmSync(root, { recursive: true, force: true })) + +describe("mapleSourceMaps", () => { + it("injects debug ids and moves every map out of the output, still mapping to the source", async () => { + await build({ + root, + configFile: false, + logLevel: "silent", + plugins: [mapleSourceMaps()], + build: { outDir: "dist", rolldownOptions: { input: join(root, "src/main.js") } }, + }) + + const output = walk(join(root, "dist")) + expect(Arr.filter(output, Str.endsWith(".map"))).toEqual([]) + const [jsFile] = Arr.filter(output, Str.endsWith(".js")) + expect(jsFile).toBeDefined() + const code = readFileSync(join(root, "dist", jsFile ?? ""), "utf8") + expect(code).toContain("_mapleDebugIds") + const debugId = /\/\/# debugId=([0-9a-f-]{36})/.exec(code)?.[1] + expect(debugId).toBeDefined() + expect(code).not.toContain("sourceMappingURL") + + const mapsDir = join(root, ".maple/sourcemaps/dist") + const manifest = JSON.parse(readFileSync(join(mapsDir, "maple-sourcemaps.json"), "utf8")) + expect(manifest).toEqual({ version: 1, files: [{ file: jsFile, debugId, map: `${jsFile}.map` }] }) + const map = JSON.parse(readFileSync(join(mapsDir, `${jsFile}.map`), "utf8")) + expect([map.debugId, map.debug_id, map.x_maple_shifted]).toEqual([debugId, debugId, debugId]) + expect(Str.startsWith(";")(map.mappings)).toBe(true) + + // The thrown message's generated position still maps to line 3 of the source. + const lines = Str.split("\n")(code) + const line = Arr.findFirstIndex(lines, Str.includes("boom-from-line-3")) + expect(line._tag).toBe("Some") + const generatedLine = line._tag === "Some" ? line.value : -1 + const column = Option.getOrElse(Str.indexOf("boom-from-line-3")(lines[generatedLine] ?? ""), () => -1) + const position = originalPositionFor(new TraceMap(map), { line: generatedLine + 1, column }) + expect([Str.endsWith("src/main.js")(position.source ?? ""), position.line]).toEqual([true, 3]) + }) + + it("relocates every output of a build that writes several into one dir", async () => { + await build({ + root, + configFile: false, + logLevel: "silent", + plugins: [mapleSourceMaps({ mapsDir: "maps" })], + build: { + outDir: "dist", + rolldownOptions: { + input: join(root, "src/main.js"), + output: [ + { dir: join(root, "dist"), entryFileNames: "esm-[name].js", format: "es" }, + { dir: join(root, "dist"), entryFileNames: "cjs-[name].js", format: "cjs" }, + ], + }, + }, + }) + const output = walk(join(root, "dist")) + expect(Arr.filter(output, Str.endsWith(".map"))).toEqual([]) + const manifest = decodeManifest(readFileSync(join(root, "maps/maple-sourcemaps.json"), "utf8")) + expect( + Arr.sort( + Arr.map(manifest.files, (file) => file.file), + Order.String, + ), + ).toEqual(["cjs-main.js", "esm-main.js"]) + expect(Arr.sort(Arr.filter(walk(join(root, "maps")), Str.endsWith(".map")), Order.String)).toEqual([ + "cjs-main.js.map", + "esm-main.js.map", + ]) + }) +}) + +describe("processBuildOutputs", () => { + const writeOutput = (dir: string) => { + mkdirSync(dir, { recursive: true }) + writeFileSync(join(dir, "a.js"), "a()\n") + writeFileSync( + join(dir, "a.js.map"), + JSON.stringify({ version: 3, sources: ["a.ts"], mappings: "AAAA" }), + ) + } + const run = (outDirs: ReadonlyArray, mapsDir: string) => + Effect.runPromise( + Effect.result(processBuildOutputs(outDirs, mapsDir)).pipe(Effect.provide(NodeServices.layer)), + ) + + it("refuses a maps dir that is, holds or sits inside the output, touching nothing", async () => { + const dist = join(root, "dist") + writeOutput(dist) + for (const mapsDir of [dist, join(dist, "maps"), root]) { + const result = await run([dist], mapsDir) + expect(Result.isFailure(result) ? result.failure._tag : "ok").toBe( + "@maple/sourcemaps/SourceMapsDirOverlapError", + ) + } + expect(Arr.sort(walk(dist), Order.String)).toEqual(["a.js", "a.js.map"]) + }) + + it("replaces only the previous build's maps, leaving other files in the maps dir", async () => { + const dist = join(root, "dist") + const maps = join(root, "maps") + mkdirSync(maps) + writeFileSync(join(maps, "keep.txt"), "mine") + writeOutput(dist) + await run([dist], maps) + expect(Arr.sort(walk(maps), Order.String)).toEqual(["a.js.map", "keep.txt", "maple-sourcemaps.json"]) + // The next build no longer emits a.js: its map goes, the unrelated file stays. + rmSync(dist, { recursive: true, force: true }) + mkdirSync(dist) + writeFileSync(join(dist, "b.js"), "b()\n") + writeFileSync( + join(dist, "b.js.map"), + JSON.stringify({ version: 3, sources: ["b.ts"], mappings: "AAAA" }), + ) + await run([dist], maps) + expect(Arr.sort(walk(maps), Order.String)).toEqual(["b.js.map", "keep.txt", "maple-sourcemaps.json"]) + }) +}) diff --git a/packages/alchemy-maple/tsconfig.json b/packages/alchemy-maple/tsconfig.json index 8bd7bfb1c3..df0d0b935a 100644 --- a/packages/alchemy-maple/tsconfig.json +++ b/packages/alchemy-maple/tsconfig.json @@ -7,6 +7,7 @@ "lib": ["ES2024"], "types": ["bun", "node"], "moduleResolution": "bundler", + "allowImportingTsExtensions": true, "verbatimModuleSyntax": true, "noEmit": true, "skipLibCheck": true, diff --git a/packages/alchemy-maple/tsdown.config.ts b/packages/alchemy-maple/tsdown.config.ts index 7e912d931f..b5fc840b4e 100644 --- a/packages/alchemy-maple/tsdown.config.ts +++ b/packages/alchemy-maple/tsdown.config.ts @@ -12,6 +12,7 @@ export default defineConfig({ telemetry: "./src/Telemetry.ts", local: "./src/Local.ts", "local-sidecar": "./src/LocalSidecar.ts", + vite: "./src/Vite.ts", }, format: "esm", dts: { tsconfig: "../../tsconfig.alchemy-maple.json" }, @@ -22,8 +23,8 @@ export default defineConfig({ loader: { ".sql": "text" }, define: { __CHDB_VERSION__: JSON.stringify(libchdbVersion) }, deps: { - neverBundle: ["effect", /^@effect\//, "alchemy", "@maple-dev/effect-sdk", /^bun:/], + neverBundle: ["effect", /^@effect\//, "alchemy", "@maple-dev/effect-sdk", "vite", /^bun:/], alwaysBundle: [/^@maple\//, /^@maple-dev\/effect-orm/], - onlyImport: ["effect", /^@effect\//, "alchemy", "@maple-dev/effect-sdk", /^node:/, /^bun:/], + onlyImport: ["effect", /^@effect\//, "alchemy", "@maple-dev/effect-sdk", "vite", /^node:/, /^bun:/], }, }) diff --git a/packages/browser/scripts/size.ts b/packages/browser/scripts/size.ts index 748c2bd99e..505831439d 100644 --- a/packages/browser/scripts/size.ts +++ b/packages/browser/scripts/size.ts @@ -91,8 +91,10 @@ const BUDGET = { * `errors.ignoreNetworkFailuresFor`, sampled-out sessions included (~0.55 kB). * 26.5 since 2026-11: `persistence: "cookieless"` (the row visitor rule, memory-wins * guard against older copies) measured 26.07 kB. + * 35.5 since 2026-11: main measured 34.97 kB; `maple.exception.debug_ids` (source map debug + * ids on every exception event, on the capture path) adds ~0.2 kB. */ - firstParty: 35, + firstParty: 35.5, } /** How close to a ceiling counts as worth warning about. */ diff --git a/packages/browser/src/__fixtures__/debug-id-chunk.js b/packages/browser/src/__fixtures__/debug-id-chunk.js new file mode 100644 index 0000000000..139bc4978b --- /dev/null +++ b/packages/browser/src/__fixtures__/debug-id-chunk.js @@ -0,0 +1,12 @@ +/* oxlint-disable */ +// A built chunk after `maple sourcemaps inject`: it throws for real, then carries the appended snippet. +window.__chunkError = Promise.resolve() + .then(function crash() { + throw new Error("from chunk") + }) + .catch(function (error) { + return error + }) +// prettier-ignore +!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},s=(new g.Error).stack;s&&(g._mapleDebugIds=g._mapleDebugIds||{},g._mapleDebugIds[s]="0b6c7a1e-58a4-4c1e-9d0b-2f3c4d5e6f70")}catch(e){}}() +//# debugId=0b6c7a1e-58a4-4c1e-9d0b-2f3c4d5e6f70 diff --git a/packages/browser/src/debug-ids.test.ts b/packages/browser/src/debug-ids.test.ts new file mode 100644 index 0000000000..9a47310768 --- /dev/null +++ b/packages/browser/src/debug-ids.test.ts @@ -0,0 +1,115 @@ +import { afterEach, describe, expect, it } from "vitest" +import { debugIdsOf, resetDebugIdsForTests } from "./debug-ids" +import { InMemorySpanExporter, SimpleSpanProcessor } from "./sdk/testing" +import { TracerProvider } from "./sdk/tracer" + +const owner: Record = globalThis + +const APP = "https://cdn.test/assets/app-1a2b.js" +const VENDOR = "https://cdn.test/assets/vendor-9f8e.js?v=3" +const APP_ID = "11111111-1111-4111-8111-111111111111" +const VENDOR_ID = "22222222-2222-4222-8222-222222222222" + +const v8Key = (url: string) => `Error\n at ${url}:1:345\n at https://cdn.test/assets/loader.js:9:9` + +afterEach(() => { + delete owner._mapleDebugIds + delete owner._sentryDebugIds + resetDebugIdsForTests() +}) + +describe("debugIdsOf", () => { + it("reads the file URL from V8, Firefox and Safari registration stacks", () => { + owner._mapleDebugIds = { + [v8Key(APP)]: APP_ID, + [`@${VENDOR}:1:12\n`]: VENDOR_ID, + "global code@https://cdn.test/assets/safari.js:1:88": "33333333-3333-4333-8333-333333333333", + } + const stack = [ + "TypeError: boom", + ` at render (${APP}:4:10)`, + `handler@${VENDOR}:2:3`, + "global code@https://cdn.test/assets/safari.js:7:1", + ].join("\n") + + expect(debugIdsOf(stack)).toBe( + JSON.stringify({ + [APP]: APP_ID, + [VENDOR]: VENDOR_ID, + "https://cdn.test/assets/safari.js": "33333333-3333-4333-8333-333333333333", + }), + ) + }) + + it("keeps a query string as part of the URL", () => { + owner._mapleDebugIds = { [v8Key(VENDOR)]: VENDOR_ID } + + expect(debugIdsOf(`Error\n at ${VENDOR}:1:1`)).toBe(JSON.stringify({ [VENDOR]: VENDOR_ID })) + expect(debugIdsOf("Error\n at https://cdn.test/assets/vendor-9f8e.js:1:1")).toBeUndefined() + }) + + it("includes only scripts that appear in the stack", () => { + owner._mapleDebugIds = { [v8Key(APP)]: APP_ID, [v8Key(VENDOR)]: VENDOR_ID } + + expect(debugIdsOf(`Error\n at f (${APP}:1:1)`)).toBe(JSON.stringify({ [APP]: APP_ID })) + expect(debugIdsOf("Error\n at f (https://cdn.test/other.js:1:1)")).toBeUndefined() + }) + + it("is absent when nothing is registered", () => { + expect(debugIdsOf(`Error\n at f (${APP}:1:1)`)).toBeUndefined() + }) + + it("picks up a chunk registered after the first lookup", () => { + const registry = { [v8Key(APP)]: APP_ID } + owner._mapleDebugIds = registry + const stack = `Error\n at f (${APP}:1:1)\n at g (${VENDOR}:1:1)` + expect(debugIdsOf(stack)).toBe(JSON.stringify({ [APP]: APP_ID })) + + registry[v8Key(VENDOR)] = VENDOR_ID + + expect(debugIdsOf(stack)).toBe(JSON.stringify({ [APP]: APP_ID, [VENDOR]: VENDOR_ID })) + }) + + it("reads Sentry's registry too, Maple's winning for the same script", () => { + owner._sentryDebugIds = { [v8Key(APP)]: "sentry-app", [v8Key(VENDOR)]: VENDOR_ID } + owner._mapleDebugIds = { [`${v8Key(APP)}\n at extra.js:1:1`]: APP_ID } + + expect(debugIdsOf(`Error\n at f (${APP}:1:1)\n at ${VENDOR}:2:2`)).toBe( + JSON.stringify({ + [APP]: APP_ID, + [VENDOR]: VENDOR_ID, + }), + ) + }) + + it("ignores malformed registries and entries", () => { + owner._sentryDebugIds = "not a registry" + owner._mapleDebugIds = { [v8Key(APP)]: 42, "no frames here": VENDOR_ID } + + expect(debugIdsOf(`Error\n at f (${APP}:1:1)`)).toBeUndefined() + }) +}) + +describe("recordException", () => { + it("puts the debug ids on the exception event", () => { + owner._mapleDebugIds = { [v8Key(APP)]: APP_ID } + const exporter = new InMemorySpanExporter() + const provider = new TracerProvider({ spanProcessors: [new SimpleSpanProcessor({ exporter })] }) + const span = provider.getTracer("test").startSpan("failure") + span.recordException({ + name: "TypeError", + message: "boom", + stack: `TypeError: boom\n at ${APP}:1:1`, + }) + span.recordException({ name: "TypeError", message: "elsewhere", stack: "TypeError\n at x.js:1:1" }) + span.end() + + const [registered, unregistered] = exporter.getFinishedSpans()[0]?.events ?? [] + expect(registered?.attributes?.["maple.exception.debug_ids"]).toBe( + JSON.stringify({ + [APP]: APP_ID, + }), + ) + expect(unregistered?.attributes).not.toHaveProperty("maple.exception.debug_ids") + }) +}) diff --git a/packages/browser/src/debug-ids.ts b/packages/browser/src/debug-ids.ts new file mode 100644 index 0000000000..e4c09db0ee --- /dev/null +++ b/packages/browser/src/debug-ids.ts @@ -0,0 +1,42 @@ +// Debug ids that `maple sourcemaps inject` (or Sentry's tooling) registers per script, keyed by +// a stack captured inside that script. The backend picks the source map by id, not by URL. +import { frameUrls } from "@maple/sdk-core" + +let registered = -1 +let byUrl = new Map() + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null + +/** Script URL -> debug id, rebuilt when the registered count changes (chunks load lazily). */ +function debugIdsByUrl(): Map { + const owner: Record = globalThis + // Maple's registry last, so it wins over Sentry's for the same script. + const registries = [owner._sentryDebugIds, owner._mapleDebugIds].filter(isRecord) + // Counting keys allocates no entry pairs, so an unchanged registry costs little per exception. + const count = registries.reduce((total, registry) => total + Object.keys(registry).length, 0) + if (count !== registered) { + registered = count + byUrl = new Map() + for (const [stack, id] of registries.flatMap((registry) => Object.entries(registry))) { + const url = frameUrls(stack)[0] + if (url !== undefined && typeof id === "string") byUrl.set(url, id) + } + } + return byUrl +} + +/** `maple.exception.debug_ids` for `stack`: `{url: debugId}` JSON for each registered script in it. */ +export function debugIdsOf(stack: string): string | undefined { + const known = debugIdsByUrl() + const urls = known.size > 0 ? frameUrls(stack).filter((url) => known.has(url)) : [] + return urls.length > 0 + ? JSON.stringify(Object.fromEntries(urls.map((url) => [url, known.get(url)]))) + : undefined +} + +/** Test seam. */ +export function resetDebugIdsForTests(): void { + registered = -1 + byUrl = new Map() +} diff --git a/packages/browser/src/errors.browser.test.ts b/packages/browser/src/errors.browser.test.ts index 89e3cb7fc6..c6b15a049d 100644 --- a/packages/browser/src/errors.browser.test.ts +++ b/packages/browser/src/errors.browser.test.ts @@ -268,3 +268,29 @@ describe("filters and linked errors", () => { assert.include(String(stacktrace), "Caused by: TypeError: network down") }) }) + +describe("debug ids", () => { + it("records the debug id of a registered script the error was thrown from", async () => { + const url = new URL("./__fixtures__/debug-id-chunk.js", import.meta.url).href + const script = document.createElement("script") + script.src = url + await new Promise((resolve, reject) => { + script.addEventListener("load", resolve) + script.addEventListener("error", reject) + document.head.append(script) + }) + const owner: Record = globalThis + const error: unknown = await owner.__chunkError + + captureException(error) + + const event = exceptionEventOf(exporter.getFinishedSpans()[0]) + assert.include(String(event?.attributes?.["exception.stacktrace"]), url) + assert.deepEqual(JSON.parse(String(event?.attributes?.["maple.exception.debug_ids"])), { + [url]: "0b6c7a1e-58a4-4c1e-9d0b-2f3c4d5e6f70", + }) + script.remove() + delete owner._mapleDebugIds + delete owner.__chunkError + }) +}) diff --git a/packages/browser/src/sdk/span.ts b/packages/browser/src/sdk/span.ts index f2d7364da7..0cd28f9d21 100644 --- a/packages/browser/src/sdk/span.ts +++ b/packages/browser/src/sdk/span.ts @@ -15,6 +15,7 @@ import { SpanStatusCode, type TimeInput, } from "@opentelemetry/api" +import { debugIdsOf } from "../debug-ids" import { addAttribute, cleanAttributes } from "./attributes" import { addHrTimes, hrTime, hrTimeDuration, isHrTime, isTimeInput, millisToHrTime } from "./time" @@ -262,6 +263,8 @@ export class SpanImpl implements Span { } if (exception.stack !== undefined && exception.stack !== "") { attributes["exception.stacktrace"] = exception.stack + const debugIds = debugIdsOf(exception.stack) + if (debugIds !== undefined) attributes["maple.exception.debug_ids"] = debugIds } } if (attributes["exception.type"] !== undefined || attributes["exception.message"] !== undefined) { diff --git a/packages/domain/package.json b/packages/domain/package.json index 3105ac6bdd..f166ff86f4 100644 --- a/packages/domain/package.json +++ b/packages/domain/package.json @@ -130,6 +130,7 @@ "@maple/primitives": "workspace:*", "@maple/query-model": "workspace:*", "@maple/security-audit": "workspace:*", + "@maple/sourcemaps": "workspace:*", "@maple/strings": "workspace:*", "@maple/widgets": "workspace:*", "effect": "catalog:effect", diff --git a/packages/domain/src/http/source-maps.ts b/packages/domain/src/http/source-maps.ts index f2e8006768..596d2ecba0 100644 --- a/packages/domain/src/http/source-maps.ts +++ b/packages/domain/src/http/source-maps.ts @@ -2,11 +2,7 @@ import { Schema } from "effect" import { SourceMapFileId } from "@maple/primitives" import { HttpTaggedError } from "./error-policy" -/** - * Largest source map one upload may carry: also the largest symbolication loads, so an upload that - * succeeds can always be used. - */ -export const SOURCE_MAP_MAX_BYTES = 10 * 1024 * 1024 +export { SOURCE_MAP_MAX_BYTES } from "@maple/sourcemaps/limits" /** The upload is not a usable source map, or its parameters do not identify one. */ export class SourceMapInvalidError extends HttpTaggedError()( diff --git a/packages/infra/package.json b/packages/infra/package.json index 8714fcf839..f6baf146fc 100644 --- a/packages/infra/package.json +++ b/packages/infra/package.json @@ -20,6 +20,7 @@ "./secret-slot-keys": "./src/secret-slot-keys.ts", "./secrets": "./src/secrets.ts", "./security-baseline": "./src/aws/security-baseline.ts", + "./self-source-maps": "./src/cloudflare/self-source-maps.ts", "./worker-build": "./src/cloudflare/worker-build.ts", "./worker-runtime": "./src/cloudflare/worker-runtime.ts", "./worker-telemetry": "./src/cloudflare/worker-telemetry.ts", diff --git a/packages/infra/src/cloudflare/self-source-maps.ts b/packages/infra/src/cloudflare/self-source-maps.ts new file mode 100644 index 0000000000..1622030d0c --- /dev/null +++ b/packages/infra/src/cloudflare/self-source-maps.ts @@ -0,0 +1,51 @@ +// The dashboard's own source maps, uploaded into Maple's org after each prd build of `web`. +import * as Maple from "@maple-dev/alchemy" +import { Effect, Layer, Option, Redacted } from "effect" +import { FetchHttpClient } from "effect/http" +import { commitSha } from "../env.ts" +import { resolveAs } from "../secret-guard.ts" +import { MapleSourceMapsApiKey } from "../secrets.ts" + +/** The deploy's read of the upload key: absent outside prd, where nothing uploads. */ +export const webSourceMapsApiKey = MapleSourceMapsApiKey.optionalValue + +/** + * Maple's providers on the upload key. Without one the key is empty and no `Maple.*` resource is + * declared, so the client is never called. + */ +export const selfMapleProviders = Maple.providersWithDependencies().pipe( + Layer.provide(FetchHttpClient.layer), + Layer.provide( + Layer.effect( + Maple.MapleEnvironment, + Effect.map(resolveAs("web", webSourceMapsApiKey), (key) => ({ + baseUrl: Maple.DEFAULT_BASE_URL, + apiKey: Option.getOrElse(key, () => Redacted.make("")), + })), + ).pipe(Layer.orDie), + ), +) + +/** + * Uploads web's maps from `dir` under the service and release its browser telemetry reports + * (`service.version` is `VITE_COMMIT_SHA`, resolved here as `web`'s env resolves it). A no-op + * without the key. + */ +export const uploadWebSourceMaps = (input: { + readonly dir: string + readonly service: string + readonly after: unknown +}) => + Effect.gen(function* () { + const key = yield* resolveAs("web", webSourceMapsApiKey) + if (Option.isNone(key)) return + const release = yield* commitSha("VITE_COMMIT_SHA") + yield* Maple.SourceMaps("web-sourcemaps", { + dir: input.dir, + service: input.service, + ...(release === "" ? undefined : { release }), + // web's telemetry reports no debug ids: each release keeps its own id-less maps. + matchBy: "release", + after: input.after, + }) + }) diff --git a/packages/infra/src/secrets.ts b/packages/infra/src/secrets.ts index b058c42fab..e3a7af2fdb 100644 --- a/packages/infra/src/secrets.ts +++ b/packages/infra/src/secrets.ts @@ -158,6 +158,14 @@ export class OtelIngestKey extends Secret()("MAPLE_OTEL_INGEST_KE sharesProdValueWith: ["dev", "preview"], }) {} +// Uploads the dashboard's source maps into Maple's own org at deploy (`source_maps:write` only). Prd +// alone: dev and preview builds upload nothing. +export class MapleSourceMapsApiKey extends Secret()("MAPLE_SOURCEMAPS_API_KEY", { + issuer: "maple", + consumers: ["web"], + environments: PRD_ONLY, +}) {} + export class ProductEventsIngestKey extends Secret()( "MAPLE_PRODUCT_EVENTS_INGEST_KEY", // ai and alerting stamp an org's first data, which emits `first_data_received`. diff --git a/packages/sourcemaps/package.json b/packages/sourcemaps/package.json new file mode 100644 index 0000000000..7151a5c56f --- /dev/null +++ b/packages/sourcemaps/package.json @@ -0,0 +1,21 @@ +{ + "name": "@maple/sourcemaps", + "private": true, + "description": "Debug-id injection for built JavaScript and its source maps, shared by the Maple CLI and the Alchemy Vite plugin. Private: consumers bundle it.", + "type": "module", + "sideEffects": false, + "exports": { + ".": "./src/index.ts", + "./limits": "./src/limits.ts" + }, + "scripts": { + "typecheck": "tsrs --noEmit" + }, + "dependencies": { + "effect": "catalog:effect" + }, + "devDependencies": { + "@types/node": "catalog:tooling", + "typescript": "catalog:tooling" + } +} diff --git a/packages/sourcemaps/src/index.ts b/packages/sourcemaps/src/index.ts new file mode 100644 index 0000000000..aeb37ac5f0 --- /dev/null +++ b/packages/sourcemaps/src/index.ts @@ -0,0 +1,2 @@ +export * from "./inject.ts" +export * from "./relocate.ts" diff --git a/packages/sourcemaps/src/inject.ts b/packages/sourcemaps/src/inject.ts new file mode 100644 index 0000000000..29acd23b7a --- /dev/null +++ b/packages/sourcemaps/src/inject.ts @@ -0,0 +1,390 @@ +// Give built JS files a debug id derived from the file and its map, registered at runtime, so the +// backend can pick each file's source map by id. Shared by `maple sourcemaps` and the Vite plugin. + +import { createHash } from "node:crypto" +import { Array as Arr, Effect, Option, Order, Predicate, Result, Schema, String as Str } from "effect" +import { FileSystem } from "effect/FileSystem" +import { Path } from "effect/Path" + +export const JS_EXTENSIONS: ReadonlyArray = [".js", ".mjs", ".cjs"] + +/** Reading or writing the build output failed. */ +export class SourceMapsFileError extends Schema.TaggedError()( + "@maple/sourcemaps/SourceMapsFileError", + { + message: Schema.String, + path: Schema.String, + cause: Schema.optionalKey(Schema.Defect()), + }, +) {} + +// `\r?` before `$`: with the `m` flag `$` stops at `\n`, so CRLF files keep a `\r` there. +const DEBUG_ID_COMMENT = /^\/\/# debugId=([0-9a-fA-F-]{36})[ \t]*\r?$/m +const SOURCE_MAPPING_URL = /^\/\/[#@] sourceMappingURL=(\S+)[ \t]*\r?$/gm +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/ +const REGISTERED_ID = /_(?:maple|sentry)DebugIds\[[^\]]*\]\s*=\s*["']([0-9a-fA-F-]{36})["']/ + +const MapObject = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)) +const decodeMap = Schema.decodeUnknownResult(MapObject) +const encodeMap = Schema.encodeResult(MapObject) + +/** The map as JSON without its `debugId` / `debug_id`, so writing an id never changes the hash. */ +const canonicalMap = (mapText: string): string => + Result.match(decodeMap(mapText), { + onFailure: () => mapText, + onSuccess: ({ debugId: _a, debug_id: _b, x_maple_shifted: _c, ...rest }) => + Result.getOrElse(encodeMap(rest), () => mapText), + }) + +/** + * sha256 of the JS file and its map as a lowercase UUID. The version (4) and variant nibbles are set + * so the id passes strict UUID validators; the rest is the hash, so the same build always gets the + * same id, and identical JS with another map (comments moved, sources changed) gets another. + */ +export const debugIdFor = (code: Uint8Array | string, mapText: string): string => { + const h = createHash("sha256").update(code).update("\u0000").update(canonicalMap(mapText)).digest("hex") + const part = (start: number, end: number) => Str.slice(start, end)(h) + const variant = ((Number.parseInt(part(16, 17), 16) & 0x3) | 0x8).toString(16) + return `${part(0, 8)}-${part(8, 12)}-4${part(13, 16)}-${variant}${part(17, 20)}-${part(20, 32)}` +} + +export const debugIdSnippet = (id: string): string => + `;!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},s=(new g.Error).stack;s&&(g._mapleDebugIds=g._mapleDebugIds||{},g._mapleDebugIds[s]="${id}")}catch(e){}}();` + +/** The id in an existing `//# debugId=` comment, else the one a runtime registration assigns. */ +export const existingDebugId = (code: string): Option.Option => + Option.firstSomeOf([ + Option.fromNullishOr(DEBUG_ID_COMMENT.exec(code)?.[1]), + Option.fromNullishOr(REGISTERED_ID.exec(code)?.[1]), + ]).pipe( + Option.map(Str.toLowerCase), + Option.filter((id) => UUID.test(id)), + ) + +/** The last `//# sourceMappingURL=` comment: its value and where its line starts. */ +export const sourceMappingUrl = ( + code: string, +): Option.Option<{ readonly url: string; readonly index: number }> => + Arr.last(Arr.fromIterable(Str.matchAll(SOURCE_MAPPING_URL)(code))).pipe( + Option.flatMap((match) => + Option.all({ url: Option.fromNullishOr(match[1]), index: Option.fromNullishOr(match.index) }), + ), + ) + +/** + * Whether the file registers `id` at runtime (ours or Sentry's snippet assigning it into the + * debug id map), which a bare `//# debugId=` comment does not. A bundled SDK that only reads + * the map does not count. `id` is a UUID, so it needs no escaping. + */ +export const hasRuntimeRegistration = (code: string, id: string): boolean => + new RegExp(`_(?:maple|sentry)DebugIds\\[[^\\]]*\\]\\s*=\\s*["']${id}["']`, "i").test(code) + +/** Where trailing comments start: the first of an existing debugId and the last sourceMappingURL. */ +const trailerIndex = (code: string): Option.Option => + Arr.head( + Arr.sort( + [ + ...Option.toArray(Option.fromNullishOr(DEBUG_ID_COMMENT.exec(code)?.index)), + ...Option.toArray(Option.map(sourceMappingUrl(code), (url) => url.index)), + ], + Order.Number, + ), + ) + +const insertBeforeTrailer = (code: string, block: string): string => + Option.match(trailerIndex(code), { + onSome: (index) => `${Str.slice(0, index)(code)}${block}${Str.slice(index)(code)}`, + onNone: () => `${code}${code === "" || Str.endsWith("\n")(code) ? "" : "\n"}${block}`, + }) + +/** + * Whether the snippet can go on a new first line: not above a shebang, and not above a directive + * prologue (`"use strict"` and the like), which only counts as one at the top. + */ +export const canPrepend = (code: string): boolean => !Str.startsWith("#!")(code) && !startsWithString(code) + +/** Whether the first token after whitespace and comments is a string literal; one linear pass. */ +const startsWithString = (code: string): boolean => { + const rest = Str.trimStart(code) + if (Str.startsWith("//")(rest)) { + return Option.match(Str.indexOf("\n")(rest), { + onNone: () => false, + onSome: (end) => startsWithString(Str.slice(end + 1)(rest)), + }) + } + if (Str.startsWith("/*")(rest)) { + return Option.match(Str.indexOf("*/")(Str.slice(2)(rest)), { + onNone: () => false, + onSome: (end) => startsWithString(Str.slice(end + 4)(rest)), + }) + } + return Str.startsWith('"')(rest) || Str.startsWith("'")(rest) +} + +/** + * `prepend`: the snippet on a new first line, so the id is registered before the module's own code + * runs (a throw while it loads still reports it); every line moves down one, which the map's + * mappings must follow (`shiftMappings`). `append`: the snippet after the code, before the trailing + * debugId / sourceMappingURL comments, so nothing moves. Either way the `//# debugId=` comment is + * added near the end unless the file has one. + */ +export const injectCode = (code: string, id: string, mode: "prepend" | "append"): string => { + const hasComment = DEBUG_ID_COMMENT.test(code) + if (mode === "prepend") { + const tagged = hasComment ? code : insertBeforeTrailer(code, `//# debugId=${id}\n`) + return `${debugIdSnippet(id)}\n${tagged}` + } + return insertBeforeTrailer( + code, + hasComment ? `${debugIdSnippet(id)}\n` : `${debugIdSnippet(id)}\n//# debugId=${id}\n`, + ) +} + +/** Mappings for code one line lower: an empty first generated line. */ +export const shiftMappings = (mappings: string): string => `;${mappings}` + +/** The map's own debug id (`debugId`, else `debug_id`), or `None` when it has none or is not JSON. */ +export const mapDebugId = (mapText: string): Option.Option => + Result.getSuccess(decodeMap(mapText)).pipe( + Option.flatMap((map) => + Option.firstSomeOf([ + Option.liftPredicate(map["debugId"], Predicate.isString), + Option.liftPredicate(map["debug_id"], Predicate.isString), + ]), + ), + Option.map(Str.toLowerCase), + Option.filter((id) => UUID.test(id)), + ) + +/** Whether the map is an index map (`sections`), which the server refuses. */ +export const isIndexMap = (mapText: string): boolean => + Result.match(decodeMap(mapText), { + onFailure: () => false, + onSuccess: (map) => map["sections"] !== undefined, + }) + +/** A version 3 source map as a JSON object; anything else is never rewritten. */ +const decodeV3Map = (mapText: string) => + Option.filter(Result.getSuccess(decodeMap(mapText)), (map) => map["version"] === 3) + +const isJsFile = (file: string): boolean => Arr.some(JS_EXTENSIONS, (ext) => Str.endsWith(ext)(file)) + +const isLocalReference = (url: string): boolean => !/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(url) + +const decodeUrlPath = (url: string): string => + Result.getOrElse( + Result.try(() => decodeURIComponent(url)), + () => url, + ) + +export const fileError = (path: string, verb: string) => (cause: unknown) => + new SourceMapsFileError({ message: `could not ${verb} ${path}`, path, cause }) + +/** Every file below `dir` that passes `keep`, relative to `dir` with `/` separators, sorted. */ +export const listFiles = (dir: string, keep: (file: string) => boolean) => + Effect.gen(function* () { + const fs = yield* FileSystem + const files = yield* fs + .readDirectory(dir, { recursive: true }) + .pipe(Effect.mapError(fileError(dir, "list"))) + return Arr.sort( + Arr.filter( + Arr.map(files, (f) => Str.replaceAll("\\", "/")(f)), + (f) => keep(f) && !Str.includes("/node_modules/")(`/${f}`), + ), + Order.String, + ) + }) + +export interface JsWithMap { + /** Relative to the walked directory, with `/` separators. */ + readonly file: string + readonly jsPath: string + readonly code: string + readonly bytes: Uint8Array + readonly mapPath: Option.Option + /** The map the file names, refused because it lies outside the build directory. */ + readonly refusedMap: Option.Option +} + +/** Whether `target` lies below `root`, both lexically and once symlinks are followed. */ +const isInside = (root: string, target: string) => + Effect.gen(function* () { + const fs = yield* FileSystem + const path = yield* Path + const within = (base: string, file: string) => + Option.isSome(path.resolveWithin(base, path.relative(base, file))) && + path.resolve(base) !== path.resolve(file) + if (!within(root, target)) return false + const real = yield* Effect.all([fs.realPath(root), fs.realPath(target)]).pipe(Effect.option) + return Option.isSome(real) && within(real.value[0], real.value[1]) + }) + +/** + * The JS file's map: the local file its sourceMappingURL names, else `.map`, if it exists. A + * named map outside `root` (a `..` escape, an absolute path, a symlink) is refused, never read. + */ +const resolveMap = (root: string, jsPath: string, code: string) => + Effect.gen(function* () { + const fs = yield* FileSystem + const path = yield* Path + const referenced = Option.filter(sourceMappingUrl(code), ({ url }) => isLocalReference(url)).pipe( + Option.map(({ url }) => + path.resolve(path.dirname(jsPath), decodeUrlPath(Str.replace(/[?#].*$/, "")(url))), + ), + ) + const exists = (candidate: string) => fs.exists(candidate).pipe(Effect.orElseSucceed(() => false)) + if (Option.isSome(referenced) && (yield* exists(referenced.value))) { + return (yield* isInside(root, referenced.value)) + ? { mapPath: referenced, refusedMap: Option.none() } + : { mapPath: Option.none(), refusedMap: referenced } + } + const sibling = `${jsPath}.map` + if (!(yield* exists(sibling))) + return { mapPath: Option.none(), refusedMap: Option.none() } + return (yield* isInside(root, sibling)) + ? { mapPath: Option.some(sibling), refusedMap: Option.none() } + : { mapPath: Option.none(), refusedMap: Option.some(sibling) } + }) + +/** Every `*.js`/`*.mjs`/`*.cjs` file below `dir`, read, with the map it points at (if any). */ +export const findJsFiles = (dir: string) => + Effect.gen(function* () { + const fs = yield* FileSystem + const path = yield* Path + const files = yield* listFiles(dir, isJsFile) + return yield* Effect.forEach(files, (file) => + Effect.gen(function* () { + const jsPath = path.join(dir, file) + const bytes = yield* fs.readFile(jsPath).pipe(Effect.mapError(fileError(jsPath, "read"))) + const code = new TextDecoder().decode(bytes) + const { mapPath, refusedMap } = yield* resolveMap(dir, jsPath, code) + return { file, jsPath, code, bytes, mapPath, refusedMap } satisfies JsWithMap + }), + ) + }) + +/** How many JS files name each map: a map two files share cannot carry either file's id. */ +export const mapUsers = (files: ReadonlyArray): ReadonlyMap => + Arr.reduce( + Arr.getSomes(Arr.map(files, (js) => js.mapPath)), + new Map(), + (users, mapPath) => users.set(mapPath, (users.get(mapPath) ?? 0) + 1), + ) + +// --------------------------------------------------------------------------- +// inject +// --------------------------------------------------------------------------- + +export type InjectStatus = "injected" | "already_injected" | "no_map" | "invalid_map" | "unsafe_map" + +export interface InjectResult { + readonly file: string + readonly status: InjectStatus + readonly debugId: Option.Option + /** True when the map gained `debugId`/`debug_id` (or would, under --dry-run). */ + readonly mapUpdated: boolean + /** The file's map: the one injected, or the one refused or not a version 3 JSON object. */ + readonly mapPath: Option.Option +} + +/** The map carrying `id`, its mappings one line lower when `shift`, marked as moved when `moved`. */ +const taggedMap = ( + map: { readonly [key: string]: unknown }, + id: string, + shift: boolean, + moved: boolean, +): Result.Result => { + const mappings = map["mappings"] + const tagged = { ...map, debugId: id, debug_id: id, ...(moved ? { [SHIFTED_FIELD]: id } : undefined) } + return encodeMap( + shift && Predicate.isString(mappings) ? { ...tagged, mappings: shiftMappings(mappings) } : tagged, + ) +} + +/** Marks a map whose mappings were moved one line down for `id`'s snippet, so they never move twice. */ +const SHIFTED_FIELD = "x_maple_shifted" + +/** Replaces `path` whole: a failed write leaves the old file, never a half-written one. */ +const writeAtomically = (path: string, content: string) => + Effect.gen(function* () { + const fs = yield* FileSystem + const temporary = `${path}.maple-tmp` + yield* fs.writeFileString(temporary, content) + yield* fs.rename(temporary, path) + }).pipe(Effect.mapError(fileError(path, "write"))) + +const injectOne = (js: JsWithMap, shared: boolean, dryRun: boolean) => + Effect.gen(function* () { + const fs = yield* FileSystem + const skip = (status: InjectStatus, mapPath: Option.Option): InjectResult => ({ + file: js.file, + status, + debugId: Option.none(), + mapUpdated: false, + mapPath, + }) + if (Option.isSome(js.refusedMap)) return skip("unsafe_map", js.refusedMap) + if (Option.isNone(js.mapPath)) return skip("no_map", Option.none()) + const mapPath = js.mapPath.value + const mapText = yield* fs.readFileString(mapPath).pipe(Effect.mapError(fileError(mapPath, "read"))) + const map = decodeV3Map(mapText) + if (Option.isNone(map)) return skip("invalid_map", js.mapPath) + + // A map already moved for an id keeps it: its JS write failed after the map was written. + const shiftedFor = Option.filter( + Option.liftPredicate(map.value[SHIFTED_FIELD], Predicate.isString), + (id) => UUID.test(id), + ) + const previous = Option.firstSomeOf([existingDebugId(js.code), shiftedFor]) + const id = Option.getOrElse(previous, () => debugIdFor(js.bytes, mapText)) + // Rollup/Vite `sourcemapDebugIds` write the comment but nothing that reports the id at runtime. + const codeUpdated = !hasRuntimeRegistration(js.code, id) + const mappings = map.value["mappings"] + const movable = !shared && Predicate.isString(mappings) && map.value["sections"] === undefined + const hasId = map.value["debugId"] === id && map.value["debug_id"] === id + // Whether the snippet is (or goes) on the first line: lines below it are one lower. + const prepended = codeUpdated + ? movable && canPrepend(js.code) + : Str.startsWith(`${debugIdSnippet(id)}\n`)(js.code) + // Moved once only: marked by this CLI, or a registered file whose map already carries its id. + const alreadyShifted = Option.contains(shiftedFor, id) || (!codeUpdated && hasId) + const shift = prepended && movable && !alreadyShifted + // A shared map keeps no id: each file sharing it is uploaded with its own. + const mapUpdated = !shared && (shift || !hasId) + if (!dryRun) { + // The map first: a JS file pointing at a map not yet moved would map one line off. + if (mapUpdated) + yield* Effect.fromResult(taggedMap(map.value, id, shift, prepended && movable)).pipe( + Effect.mapError(fileError(mapPath, "encode")), + Effect.flatMap((content) => writeAtomically(mapPath, content)), + ) + if (codeUpdated) + yield* fs + .writeFileString(js.jsPath, injectCode(js.code, id, prepended ? "prepend" : "append")) + .pipe(Effect.mapError(fileError(js.jsPath, "write"))) + } + return { + file: js.file, + status: codeUpdated ? "injected" : "already_injected", + debugId: Option.some(id), + mapUpdated, + mapPath: js.mapPath, + } satisfies InjectResult + }) + +/** Inject debug ids into every JS file below `dir` that has a map. Re-running changes nothing. */ +export const injectDirectory = (dir: string, options: { readonly dryRun: boolean }) => + Effect.flatMap(findJsFiles(dir), (files) => { + const users = mapUsers(files) + return Effect.forEach(files, (js) => + injectOne( + js, + Option.match(js.mapPath, { + onNone: () => false, + onSome: (path) => (users.get(path) ?? 0) > 1, + }), + options.dryRun, + ), + ) + }) diff --git a/packages/sourcemaps/src/limits.ts b/packages/sourcemaps/src/limits.ts new file mode 100644 index 0000000000..74c95cde68 --- /dev/null +++ b/packages/sourcemaps/src/limits.ts @@ -0,0 +1,5 @@ +/** + * Largest source map one upload may carry: also the largest symbolication loads, so an upload that + * succeeds can always be used. Kept apart from the inject code so browser bundles can import it. + */ +export const SOURCE_MAP_MAX_BYTES = 10 * 1024 * 1024 diff --git a/packages/sourcemaps/src/relocate.ts b/packages/sourcemaps/src/relocate.ts new file mode 100644 index 0000000000..0a8a1aeae9 --- /dev/null +++ b/packages/sourcemaps/src/relocate.ts @@ -0,0 +1,125 @@ +// Moves a build's source maps out of its deployed output, so they are never served, and records +// which JS file each belongs to. The Alchemy `Maple.SourceMaps` resource uploads from there. +import { Array as Arr, Effect, Option, Schema, String as Str } from "effect" +import { FileSystem } from "effect/FileSystem" +import { Path } from "effect/Path" +import { fileError, type InjectResult, listFiles } from "./inject.ts" + +/** The manifest written next to relocated maps. */ +export const MANIFEST_FILE = "maple-sourcemaps.json" + +export const SourceMapsManifestEntry = Schema.Struct({ + /** The JS file, relative to the deployed output: the path it is served at. */ + file: Schema.String, + /** The debug id the file registers, when it has one. */ + debugId: Schema.NullOr(Schema.String), + /** The map, relative to the manifest's directory. */ + map: Schema.String, +}) +export type SourceMapsManifestEntry = typeof SourceMapsManifestEntry.Type + +export const SourceMapsManifest = Schema.Struct({ + version: Schema.Literal(1), + files: Schema.Array(SourceMapsManifestEntry), +}) +export type SourceMapsManifest = typeof SourceMapsManifest.Type + +const encodeManifest = Schema.encodeEffect(Schema.fromJsonString(SourceMapsManifest)) +const decodeManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(SourceMapsManifest)) + +/** `mapsDir` is, holds or sits inside a build output: moving maps there could delete the build. */ +export class SourceMapsDirOverlapError extends Schema.TaggedError()( + "@maple/sourcemaps/SourceMapsDirOverlapError", + { message: Schema.String, mapsDir: Schema.String, outDir: Schema.String }, +) {} + +/** One build output and what the inject did to it. */ +export interface BuildOutput { + readonly outDir: string + readonly results: ReadonlyArray +} + +/** + * Moves every `.map` below each output to the same relative path below `mapsDir` and writes one + * {@link MANIFEST_FILE} for all of them. Only the files the previous manifest listed are removed + * first, so anything else in `mapsDir` is left alone; a `mapsDir` that overlaps an output is refused + * before any file is touched. + */ +export const relocateMaps = (mapsDir: string, outputs: ReadonlyArray) => + Effect.gen(function* () { + const fs = yield* FileSystem + const path = yield* Path + const maps = path.resolve(mapsDir) + const within = (base: string, target: string) => { + const relative = path.relative(base, target) + return relative === "" || (!Str.startsWith("..")(relative) && !path.isAbsolute(relative)) + } + const overlapping = Arr.findFirst(outputs, ({ outDir }) => { + const out = path.resolve(outDir) + return within(out, maps) || within(maps, out) + }) + if (Option.isSome(overlapping)) { + return yield* new SourceMapsDirOverlapError({ + message: `The source maps directory ${maps} overlaps the build output ${overlapping.value.outDir}; choose one outside it.`, + mapsDir: maps, + outDir: overlapping.value.outDir, + }) + } + const manifestPath = path.join(maps, MANIFEST_FILE) + // The last build's maps go, by its manifest; nothing it did not write is deleted. + const previous = yield* fs.readFileString(manifestPath).pipe( + Effect.flatMap(decodeManifest), + Effect.map((manifest) => manifest.files), + Effect.orElseSucceed(() => []), + ) + yield* Effect.forEach( + previous, + (entry) => + Option.match(path.resolveWithin(maps, entry.map), { + onNone: () => Effect.void, + onSome: (file) => + fs.remove(file, { force: true }).pipe(Effect.mapError(fileError(file, "remove"))), + }), + { discard: true }, + ) + yield* fs.makeDirectory(maps, { recursive: true }).pipe(Effect.mapError(fileError(maps, "create"))) + const moved = yield* Effect.forEach(outputs, ({ outDir }) => + Effect.gen(function* () { + const files = yield* listFiles(outDir, Str.endsWith(".map")) + // Copy then delete: `mapsDir` may be on another device than the build output. + yield* Effect.forEach( + files, + (file) => + Effect.gen(function* () { + const from = path.join(outDir, file) + const to = path.join(maps, file) + yield* fs.makeDirectory(path.dirname(to), { recursive: true }) + yield* fs.copyFile(from, to) + yield* fs.remove(from) + }).pipe(Effect.mapError(fileError(path.join(outDir, file), "move"))), + { discard: true }, + ) + return files.length + }), + ) + const files = Arr.flatMap(outputs, ({ outDir, results }) => + Arr.flatMap(results, (result) => + result.status === "injected" || result.status === "already_injected" + ? Option.toArray( + Option.map(result.mapPath, (mapPath) => ({ + file: result.file, + debugId: Option.getOrNull(result.debugId), + map: Str.replaceAll("\\", "/")(path.relative(outDir, mapPath)), + })), + ) + : [], + ), + ) + const manifest = yield* encodeManifest({ version: 1, files }).pipe( + Effect.mapError(fileError(MANIFEST_FILE, "encode")), + ) + yield* fs + .writeFileString(manifestPath, manifest) + .pipe(Effect.mapError(fileError(manifestPath, "write"))) + return { moved: Arr.reduce(moved, 0, (sum, n) => sum + n), files } + }) diff --git a/packages/sourcemaps/tsconfig.json b/packages/sourcemaps/tsconfig.json new file mode 100644 index 0000000000..c5f45e7818 --- /dev/null +++ b/packages/sourcemaps/tsconfig.json @@ -0,0 +1,33 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "noUncheckedIndexedAccess": true, + "target": "ES2022", + "module": "ESNext", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": ["node"], + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "noEmit": true, + "skipLibCheck": true, + "strict": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true, + "plugins": [ + { + "name": "@effect/language-service", + "ignoreEffectWarningsInTscExitCode": false, + "includeSuggestionsInTsc": false, + "diagnosticSeverity": { + // Directives also silence oxlint rules that tsrs never reports, so tsrs flags them all as unused. + "unusedDirective": "off", + "unstableApiUsage": "off", + "schemaNumber": "off", + "schemaClassMissingBrand": "off", + "schemaSync": "off" + } + } + ] + } +} diff --git a/packages/views/src/ui/INDEX.md b/packages/views/src/ui/INDEX.md index 289af604c6..f0eea1608e 100644 --- a/packages/views/src/ui/INDEX.md +++ b/packages/views/src/ui/INDEX.md @@ -169,6 +169,7 @@ existing copies onto it (see `apps/web/CLAUDE.md`). - `packages/views/src/ui/spinner.ts` `spinner`: The loader glyph, spinning, as a status. - `packages/views/src/ui/split-button.ts` `splitButtonClass`: `SplitButton`'s two halves: the classes that join an action button and its chevron menu trigger into one control. - `packages/views/src/ui/sql-editor.ts` `sqlEditor`: `SqlEditor`: a SQL textarea whose text is drawn, syntax-highlighted, by a `
` laid under it.
+- `packages/views/src/ui/stack-frames.ts` `stackFrameRows`, `defaultOpenFrameKey`, `isStackRowOpen`, `stackFrameList`: A symbolicated stack trace as a frame list: library runs fold, in-app frames open on their code.
 - `packages/views/src/ui/stack.ts` `hstackClass`, `vstackClass`, `hstack`, `vstack`: `HStack` and `VStack`: a flex row (items centred by default) or column with its gap on the spacing scale, instead of a hand-written `flex items-center gap-2` string.
 - `packages/views/src/ui/stat-figure.ts` `statFigure`: A headline number with a muted unit.
 - `packages/views/src/ui/status-dot.ts` `statusDot`: A static, decorative status dot.
@@ -236,7 +237,7 @@ existing copies onto it (see `apps/web/CLAUDE.md`).
 - `apps/web/src/page/kit/day-label.ts` `dayKey`, `dayLabel`, `dayEyebrow`: Calendar days in a time zone, for lists grouped by day ("Today", "Yesterday", "Mon 2 Nov").
 - `apps/web/src/page/kit/destination-picker.ts` `destinationPicker`, `pickedDestination`: The alert destinations a form notifies, each removable, then an "Add destination" menu of the rest; the owner keeps the menu's Model and the chosen ids.
 - `apps/web/src/page/kit/detail-header.ts` `detailEyebrow`, `detailTitle`, `detailTitleSkeleton`, `detailActions`: A detail page's title block and its loading skeleton.
-- `apps/web/src/page/kit/disclosure-strip.ts` `disclosureStrip`: A panel's last band that opens on a long block of monospace text.
+- `apps/web/src/page/kit/disclosure-strip.ts` `disclosureStrip`, `monospaceBlock`: A panel's last band that opens on a long block of monospace text.
 - `apps/web/src/page/kit/docs.ts` `docsUrl`: Every docs page the app links to from an empty state, as a path under maple.dev.
 - `apps/web/src/page/kit/environment-switcher.ts` `environmentEntries`, `entryLabel`, `stepEnvironmentSelect`, `environmentSwitcher`: The environment switcher the overview, the service map and a service's page share.
 - `apps/web/src/page/kit/error-chip.ts` `errorChip`: Tool failures read amber: the chip class for a tool error that is not a count.
diff --git a/packages/views/src/ui/stack-frames.ts b/packages/views/src/ui/stack-frames.ts
new file mode 100644
index 0000000000..0bcc380364
--- /dev/null
+++ b/packages/views/src/ui/stack-frames.ts
@@ -0,0 +1,265 @@
+import { cn } from "@maple/ui/lib/utils"
+import type { StackFrame, StackFrameContext } from "@maple/domain/errors/js-stack"
+import { Array as Arr, Option } from "effect"
+import type { Html, HtmlBuilder } from "foldkit/html"
+import { highlightCode } from "../lib/highlight"
+import { icon } from "./icon"
+import { typography } from "./typography"
+
+// A symbolicated stack trace as a frame list: library runs fold, in-app frames open on their code.
+
+/** One row of the list: an app frame, or a run of two or more library frames folded into one. */
+export type StackFrameRow =
+	| Readonly<{ _tag: "Frame"; key: string; frame: StackFrame }>
+	| Readonly<{ _tag: "Library"; key: string; frames: ReadonlyArray }>
+
+type Run = Readonly<{ start: number; inApp: boolean; frames: ReadonlyArray }>
+
+/** The frames as rows, top of stack first: consecutive library frames fold into one row. */
+export const stackFrameRows = (frames: ReadonlyArray): ReadonlyArray => {
+	const none: ReadonlyArray = []
+	const runs = Arr.reduce(frames, none, (acc, frame, index) =>
+		Option.match(Arr.last(acc), {
+			onSome: (run) =>
+				run.inApp === frame.in_app
+					? [...Arr.dropRight(acc, 1), { ...run, frames: [...run.frames, frame] }]
+					: [...acc, { start: index, inApp: frame.in_app, frames: [frame] }],
+			onNone: () => [{ start: index, inApp: frame.in_app, frames: [frame] }],
+		}),
+	)
+	return Arr.flatMap(runs, (run): ReadonlyArray =>
+		!run.inApp && run.frames.length > 1
+			? [{ _tag: "Library", key: `lib-${run.start}`, frames: run.frames }]
+			: Arr.map(run.frames, (frame, offset) => ({
+					_tag: "Frame",
+					key: `frame-${run.start + offset}`,
+					frame,
+				})),
+	)
+}
+
+/** The row open on load: the top in-app frame, when it carries code context. */
+export const defaultOpenFrameKey = (frames: ReadonlyArray): string | null =>
+	Option.match(
+		Arr.findFirstIndex(frames, (frame) => frame.in_app),
+		{
+			onNone: () => null,
+			onSome: (index) => (frames[index]?.context === null ? null : `frame-${index}`),
+		},
+	)
+
+/** Whether a row is open: its default, flipped when its key is in `toggled`. */
+export const isStackRowOpen = (
+	frames: ReadonlyArray,
+	toggled: ReadonlyArray,
+	key: string,
+): boolean => (defaultOpenFrameKey(frames) === key) !== toggled.includes(key)
+
+export type StackFrameListOptions = Readonly<{
+	/** Top of stack first, as the backend symbolicated them. */
+	frames: ReadonlyArray
+	/** Row keys flipped from their default (the top in-app frame open, the rest closed). */
+	toggled: ReadonlyArray
+	onToggle: (key: string) => M
+	/** Prefixes the panel ids, unique on the page. */
+	idPrefix: string
+	className?: string
+}>
+
+const ROW_CLASS = "w-full min-w-0 px-4 py-1.5 text-left"
+const TOGGLE_CLASS = cn(
+	ROW_CLASS,
+	"cursor-pointer outline-none hover:bg-surface-sunken active:bg-surface-sunken focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-inset",
+)
+
+const chevron = (h: HtmlBuilder, isOpen: boolean): Html =>
+	icon(h, isOpen ? "ChevronDownIcon" : "ChevronRightIcon", { size: 12, className: "shrink-0" })
+
+const chevronSpacer = (h: HtmlBuilder): Html => h.span([h.Class("size-3 shrink-0")], [])
+
+const position = (frame: StackFrame): string =>
+	frame.line === null ? "" : frame.column === null ? `:${frame.line}` : `:${frame.line}:${frame.column}`
+
+/** The frame's function, then where it is: the original source path once a map resolved it. */
+const frameLabel = (h: HtmlBuilder, frame: StackFrame): ReadonlyArray => [
+	typography(
+		h,
+		{
+			size: "xs",
+			mono: true,
+			tone: frame.in_app ? "foreground" : "subtle",
+			weight: frame.in_app ? "medium" : "normal",
+			className: "min-w-0 break-all",
+		},
+		[frame.function ?? "(anonymous)"],
+	),
+	typography(
+		h,
+		{ size: "xs", mono: true, tone: frame.in_app ? "muted" : "subtle", className: "min-w-0 break-all" },
+		[frame.file ?? "unknown location", position(frame)],
+	),
+]
+
+const labelLine = (h: HtmlBuilder, lead: Html, label: ReadonlyArray): Html =>
+	h.span(
+		[h.Class("flex min-w-0 items-baseline gap-2")],
+		[lead, h.span([h.Class("flex min-w-0 flex-wrap items-baseline gap-x-2")], label)],
+	)
+
+const codeLine = (
+	h: HtmlBuilder,
+	number: number | null,
+	text: string,
+	isError: boolean,
+	key: string,
+	lang: string,
+): Html =>
+	h.div(
+		[
+			h.Key(key),
+			h.Class(cn("flex", isError && "bg-severity-error-a2")),
+			...(isError ? [h.DataAttribute("error-line", "")] : []),
+		],
+		[
+			h.span(
+				[
+					h.Class(
+						cn(
+							"w-12 shrink-0 pr-3 text-right tabular-nums select-none",
+							isError ? "text-severity-error" : "text-foreground-subtle",
+						),
+					),
+					h.AriaHidden(true),
+				],
+				[number === null ? "" : String(number)],
+			),
+			// Highlighted line by line: each row keeps its own number and error tint.
+			h.span(
+				[
+					h.Class("pr-4 whitespace-pre text-foreground"),
+					h.InnerHTML(text === "" ? " " : highlightCode(text, lang)),
+				],
+				[],
+			),
+		],
+	)
+
+/** The frame's source around the error line, numbered, the error line marked. */
+const codeContext = (
+	h: HtmlBuilder,
+	frame: StackFrame,
+	context: StackFrameContext,
+	id: string,
+): Html => {
+	const first = frame.line === null ? null : frame.line - context.pre.length
+	const numberAt = (offset: number) => (first === null ? null : first + offset)
+	const lang = frame.file ?? ""
+	return h.div(
+		[
+			h.Id(id),
+			h.Class(
+				"overflow-x-auto border-y border-border-subtle bg-surface-sunken py-1.5 font-mono text-xs leading-5",
+			),
+		],
+		[
+			h.div(
+				[h.Class("w-max min-w-full")],
+				[
+					...Arr.map(context.pre, (text, i) =>
+						codeLine(h, numberAt(i), text, false, `pre-${i}`, lang),
+					),
+					codeLine(h, numberAt(context.pre.length), context.line, true, "line", lang),
+					...Arr.map(context.post, (text, i) =>
+						codeLine(h, numberAt(context.pre.length + 1 + i), text, false, `post-${i}`, lang),
+					),
+				],
+			),
+		],
+	)
+}
+
+const frameRow = (
+	h: HtmlBuilder,
+	options: StackFrameListOptions,
+	frame: StackFrame,
+	key: string,
+): Html => {
+	const id = `${options.idPrefix}-${key}`
+	const context = frame.context
+	if (context === null || !frame.in_app)
+		return h.li([h.Key(key), h.Class(ROW_CLASS)], [labelLine(h, chevronSpacer(h), frameLabel(h, frame))])
+	const isOpen = isStackRowOpen(options.frames, options.toggled, key)
+	return h.li(
+		[h.Key(key)],
+		[
+			h.button(
+				[
+					h.Type("button"),
+					h.Class(TOGGLE_CLASS),
+					h.AriaExpanded(isOpen),
+					...(isOpen ? [h.AriaControls(id)] : []),
+					h.OnClick(options.onToggle(key)),
+				],
+				[labelLine(h, chevron(h, isOpen), frameLabel(h, frame))],
+			),
+			...(isOpen ? [codeContext(h, frame, context, id)] : []),
+		],
+	)
+}
+
+const libraryRow = (
+	h: HtmlBuilder,
+	options: StackFrameListOptions,
+	frames: ReadonlyArray,
+	key: string,
+): Html => {
+	const id = `${options.idPrefix}-${key}`
+	const isOpen = isStackRowOpen(options.frames, options.toggled, key)
+	return h.li(
+		[h.Key(key)],
+		[
+			h.button(
+				[
+					h.Type("button"),
+					h.Class(TOGGLE_CLASS),
+					h.AriaExpanded(isOpen),
+					...(isOpen ? [h.AriaControls(id)] : []),
+					h.OnClick(options.onToggle(key)),
+				],
+				[
+					labelLine(h, chevron(h, isOpen), [
+						typography(h, { size: "xs", tone: "muted" }, [`${frames.length} library frames`]),
+					]),
+				],
+			),
+			...(isOpen
+				? [
+						h.ol(
+							[h.Id(id), h.Class("pl-5")],
+							Arr.map(frames, (frame, i) =>
+								h.li(
+									[h.Key(`${key}-${i}`), h.Class(ROW_CLASS)],
+									[labelLine(h, chevronSpacer(h), frameLabel(h, frame))],
+								),
+							),
+						),
+					]
+				: []),
+		],
+	)
+}
+
+/**
+ * `StackFrameList`: a symbolicated stack trace, top of stack first. Library frames are muted and
+ * consecutive ones fold into one "N library frames" row; in-app frames with source open on their
+ * code context, the top one open by default. The owner's Model holds the flipped row keys.
+ */
+export const stackFrameList = (h: HtmlBuilder, options: StackFrameListOptions): Html =>
+	h.ol(
+		[h.Class(cn("min-w-0 py-1", options.className)), h.DataAttribute("slot", "stack-frames")],
+		Arr.map(stackFrameRows(options.frames), (row) =>
+			row._tag === "Frame"
+				? frameRow(h, options, row.frame, row.key)
+				: libraryRow(h, options, row.frames, row.key),
+		),
+	)
diff --git a/test/alchemy/secret-grants.test.ts b/test/alchemy/secret-grants.test.ts
index 9cd64623dd..a84fbfc47a 100644
--- a/test/alchemy/secret-grants.test.ts
+++ b/test/alchemy/secret-grants.test.ts
@@ -10,6 +10,7 @@ import { managedDbSecrets, type MapleStage, workersObservabilitySecrets } from "
 import { selfObservabilityEnv } from "@maple/infra/env"
 import type { SecretConsumer } from "@maple/infra/secret"
 import { resolveAs, resolveDerived } from "@maple/infra/secret-guard"
+import { webSourceMapsApiKey } from "@maple/infra/self-source-maps"
 import * as Catalog from "@maple/infra/secrets"
 import { aiConfiguredEnv } from "../../apps/ai/src/resources/env.ts"
 import { alertingConfiguredEnv } from "../../apps/alerting/src/resources/env.ts"
@@ -99,7 +100,8 @@ const DEPLOYABLES = {
 	sandbox: [sandboxSecrets],
 	status: onEveryStage((stage) => selfObservabilityEnv(stage, "us")),
 	"audit-archive": onEveryStage((stage) => selfObservabilityEnv(stage, "us")),
-	web: onEveryStage((stage) => selfObservabilityEnv(stage, "us")),
+	// Its Worker env, and the deploy's source map upload key (`@maple/infra/self-source-maps`).
+	web: [...onEveryStage((stage) => selfObservabilityEnv(stage, "us")), webSourceMapsApiKey],
 	landing: [landingBuildSecrets],
 	ingest: [ingestSecrets],
 	scraper: [scraperSecrets],
diff --git a/tsconfig.alchemy-maple.json b/tsconfig.alchemy-maple.json
index 741175aca5..b674d65250 100644
--- a/tsconfig.alchemy-maple.json
+++ b/tsconfig.alchemy-maple.json
@@ -10,7 +10,9 @@
 			"@maple/widgets": ["./packages/widgets/src/index.ts"],
 			"@maple/widgets/*": ["./packages/widgets/src/*"],
 			"@maple/query-model": ["./packages/query-model/src/index.ts"],
-			"@maple/primitives": ["./packages/primitives/src/index.ts"]
+			"@maple/primitives": ["./packages/primitives/src/index.ts"],
+			"@maple/sourcemaps": ["./packages/sourcemaps/src/index.ts"],
+			"@maple/sourcemaps/*": ["./packages/sourcemaps/src/*"]
 		}
 	}
 }