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/.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 005d38d470..880cb5a1a5 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -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/core/sourcemaps.ts b/apps/cli/src/core/sourcemaps.ts index ebd4c88d98..9694389f44 100644 --- a/apps/cli/src/core/sourcemaps.ts +++ b/apps/cli/src/core/sourcemaps.ts @@ -1,392 +1,7 @@ -// `maple sourcemaps inject|upload`: give built JS files a content-derived debug id, then upload each -// map to `POST /v2/source_maps` so the backend can symbolicate stack frames from those files. - -import { Array as Arr, Effect, Option, Order, Predicate, Result, Schema, String as Str } from "effect" +// `maple sourcemaps inject|upload`: the inject core is shared with the Alchemy Vite plugin. import { SOURCE_MAP_MAX_BYTES } from "@maple/domain/http" -import { FileSystem } from "effect/FileSystem" -import { Path } from "effect/Path" -export const JS_EXTENSIONS: ReadonlyArray = [".js", ".mjs", ".cjs"] +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 - -/** Reading or writing the build output failed. */ -export class SourceMapsFileError extends Schema.TaggedError()( - "@maple/cli/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) - -/** 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 }) => JSON.stringify(rest), - }) - -/** - * 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 hasher = new Bun.CryptoHasher("sha256") - hasher.update(code) - hasher.update("\u0000") - hasher.update(canonicalMap(mapText)) - const h = hasher.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, - ) - -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. */ -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 map the file names, when it was refused or is 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, -): string => { - const mappings = map["mappings"] - const tagged = { ...map, debugId: id, debug_id: id, ...(moved ? { [SHIFTED_FIELD]: id } : undefined) } - return JSON.stringify( - 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* writeAtomically(mapPath, taggedMap(map.value, id, shift, prepended && movable)) - 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: Option.none(), - } 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/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/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/*"]
 		}
 	}
 }