bugstack-sdk 2.2.1 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +139 -96
- package/README.md +496 -421
- package/bin/bugstack.cjs +6 -6
- package/dist/adapters/express/index.d.mts +2 -2
- package/dist/adapters/express/index.d.ts +2 -2
- package/dist/adapters/express/index.js +409 -43
- package/dist/adapters/express/index.js.map +1 -1
- package/dist/adapters/express/index.mjs +409 -43
- package/dist/adapters/express/index.mjs.map +1 -1
- package/dist/adapters/generic/index.d.mts +2 -2
- package/dist/adapters/generic/index.d.ts +2 -2
- package/dist/adapters/generic/index.js +457 -43
- package/dist/adapters/generic/index.js.map +1 -1
- package/dist/adapters/generic/index.mjs +454 -44
- package/dist/adapters/generic/index.mjs.map +1 -1
- package/dist/adapters/nextjs/index.d.mts +2 -2
- package/dist/adapters/nextjs/index.d.ts +2 -2
- package/dist/adapters/nextjs/index.js +409 -43
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nextjs/index.mjs +409 -43
- package/dist/adapters/nextjs/index.mjs.map +1 -1
- package/dist/build/cli.js.map +1 -1
- package/dist/build/cli.mjs.map +1 -1
- package/dist/build/upload.js.map +1 -1
- package/dist/build/upload.mjs.map +1 -1
- package/dist/{client-DoqE7sNh.d.mts → client-B9WaTEYj.d.mts} +149 -2
- package/dist/{client-DoqE7sNh.d.ts → client-B9WaTEYj.d.ts} +149 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +469 -55
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +466 -56
- package/dist/index.mjs.map +1 -1
- package/dist/next-config/index.js.map +1 -1
- package/dist/next-config/index.mjs.map +1 -1
- package/package.json +107 -104
package/dist/build/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/build/upload.ts","../../src/build/cli.ts"],"names":[],"mappings":";;;;;;AAiF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AQ,YAAY,MAAA,EAAQ;AAC9E,IAAA,SAAA,EAAU;AACV,IAAA,OAAO,CAAA;AAAA,EACT;AAEA,EAAA,IAAI,OAAA,KAAY,YAAA,IAAgB,UAAA,KAAe,QAAA,EAAU;AACvD,IAAA,OAAO,oBAAoB,IAAI,CAAA;AAAA,EACjC;AAEA,EAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,2BAAA,EAA8B,CAAC,OAAA,EAAS,UAAU,CAAA,CAAE,MAAA,CAAO,OAAO,CAAA,CAAE,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,CAAG,CAAA;AAC9F,EAAA,SAAA,EAAU;AACV,EAAA,OAAO,CAAA;AACT;AAEA,IAAA,EAAK,CAAE,IAAA;AAAA,EACL,CAAC,IAAA,KAAS,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAA;AAAA,EAC3B,CAAC,GAAA,KAAQ;AACP,IAAA,OAAA,CAAQ,MAAM,CAAA,kCAAA,EAAgC,GAAA,YAAe,QAAQ,GAAA,CAAI,KAAA,GAAQ,GAAG,CAAA,CAAE,CAAA;AACtF,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF,CAAA","file":"cli.mjs","sourcesContent":["/**\r\n * Build-time source map uploader.\r\n *\r\n * Walks a directory of compiled output looking for `.map` files and POSTs\r\n * each one to the bugstack source-map ingest endpoint. The companion\r\n * `bugstack-sdk/next-config` wrapper enables emission of these maps for\r\n * Next.js server bundles; once uploaded, the orchestrator can resolve\r\n * production stack frames like \".next/server/chunks/8393.js:1:8734\" back\r\n * to source-file positions (\"app/api/orders/route.ts:42:5\") and actually\r\n * generate fixes for bundled errors.\r\n *\r\n * This module is import-safe in any Node 18+ environment. It uses no\r\n * runtime dependencies — `node:fs/promises` + global `fetch`.\r\n */\r\n\r\nimport { readdir, readFile, stat } from \"node:fs/promises\";\r\nimport { join, relative, sep } from \"node:path\";\r\nimport { execSync } from \"node:child_process\";\r\n\r\nexport interface UploadSourceMapsOptions {\r\n /**\r\n * Project SDK key. Required. Reads BUGSTACK_PROJECT_API_KEY or\r\n * BUGSTACK_API_KEY when not supplied explicitly.\r\n */\r\n apiKey?: string;\r\n\r\n /**\r\n * Base URL of the bugstack ingest service. Reads BUGSTACK_ENDPOINT or\r\n * derives from ERROR_SERVICE_URL when not supplied. The uploader appends\r\n * `/api/sourcemaps/upload` to whatever base it gets.\r\n */\r\n endpoint?: string;\r\n\r\n /**\r\n * Release identifier (typically a commit SHA). Lets multiple deploys\r\n * coexist in the source-map table so old errors still resolve against\r\n * old maps. Auto-detected in this order:\r\n * 1. BUGSTACK_RELEASE\r\n * 2. RENDER_GIT_COMMIT\r\n * 3. VERCEL_GIT_COMMIT_SHA\r\n * 4. GITHUB_SHA\r\n * 5. `git rev-parse HEAD` (when a git checkout is present)\r\n */\r\n release?: string | null;\r\n\r\n /**\r\n * Directory to walk for `.map` files. Defaults to `.next/server`.\r\n * Override for non-Next projects (e.g. `dist` for tsc, `build` for CRA).\r\n */\r\n serverDir?: string;\r\n\r\n /**\r\n * Max concurrent uploads. Higher means faster builds, more pressure on\r\n * the ingest endpoint. Default 6 — tuned for Render's typical bandwidth.\r\n */\r\n concurrency?: number;\r\n\r\n /**\r\n * Per-file size cap in bytes. Maps larger than this are skipped with a\r\n * warning rather than failing. Default 8 MiB — covers typical\r\n * `.next/server/chunks/*.js.map` outputs comfortably.\r\n */\r\n maxBytes?: number;\r\n\r\n /**\r\n * Logger. Defaults to console. Pass a no-op logger to silence the\r\n * \"[bugstack] …\" lines in scripted environments.\r\n */\r\n log?: (message: string) => void;\r\n warn?: (message: string) => void;\r\n}\r\n\r\nexport interface UploadResult {\r\n uploaded: number;\r\n skipped: number;\r\n failed: number;\r\n totalBytes: number;\r\n elapsedMs: number;\r\n failures: Array<{ bundleFile: string; error: string }>;\r\n}\r\n\r\nconst DEFAULT_SERVER_DIR = \".next/server\";\r\nconst DEFAULT_CONCURRENCY = 6;\r\nconst DEFAULT_MAX_BYTES = 8 * 1024 * 1024;\r\nconst ENDPOINT_PATH = \"/api/sourcemaps/upload\";\r\n\r\nfunction resolveRelease(explicit?: string | null): string | null {\r\n if (explicit !== undefined) return explicit;\r\n const fromEnv =\r\n process.env.BUGSTACK_RELEASE ||\r\n process.env.RENDER_GIT_COMMIT ||\r\n process.env.VERCEL_GIT_COMMIT_SHA ||\r\n process.env.GITHUB_SHA;\r\n if (fromEnv) return fromEnv;\r\n try {\r\n return execSync(\"git rev-parse HEAD\", { stdio: [\"ignore\", \"pipe\", \"ignore\"] })\r\n .toString()\r\n .trim();\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nfunction resolveEndpoint(explicit?: string): string | null {\r\n const base =\r\n explicit ||\r\n process.env.BUGSTACK_ENDPOINT ||\r\n (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);\r\n if (!base) return null;\r\n // Strip trailing slashes + any trailing /api/capture or /capture so the\r\n // same env var that points the SDK at ingestion also works for sourcemaps.\r\n const normalised = base\r\n .replace(/\\/+$/, \"\")\r\n .replace(/\\/api\\/capture$/, \"\")\r\n .replace(/\\/capture$/, \"\");\r\n return normalised + ENDPOINT_PATH;\r\n}\r\n\r\nasync function walk(dir: string): Promise<string[]> {\r\n let entries;\r\n try {\r\n entries = await readdir(dir, { withFileTypes: true });\r\n } catch (err) {\r\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\r\n throw err;\r\n }\r\n const out: string[] = [];\r\n for (const entry of entries) {\r\n const path = join(dir, entry.name);\r\n if (entry.isDirectory()) {\r\n out.push(...(await walk(path)));\r\n } else if (entry.name.endsWith(\".map\")) {\r\n out.push(path);\r\n }\r\n }\r\n return out;\r\n}\r\n\r\nasync function pool<T, R>(\r\n items: T[],\r\n workers: number,\r\n fn: (item: T) => Promise<R>,\r\n): Promise<R[]> {\r\n const results: R[] = new Array(items.length);\r\n let i = 0;\r\n const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {\r\n while (i < items.length) {\r\n const idx = i++;\r\n results[idx] = await fn(items[idx]);\r\n }\r\n });\r\n await Promise.all(runners);\r\n return results;\r\n}\r\n\r\nfunction bundleFileFor(mapPath: string, serverDir: string): string {\r\n // Strip the serverDir prefix and the .map suffix; normalise Windows\r\n // backslashes so the bundleFile key stored on the server is portable\r\n // regardless of where the build ran.\r\n return relative(serverDir, mapPath)\r\n .replace(/\\.map$/, \"\")\r\n .split(sep)\r\n .join(\"/\");\r\n}\r\n\r\n/**\r\n * Upload every `.map` file under `serverDir` to the bugstack source-map\r\n * endpoint. Tolerant: never throws on individual file failures, returns\r\n * a summary the caller can decide what to do with.\r\n *\r\n * Throws only on hard configuration errors (no API key, no resolvable\r\n * endpoint, serverDir totally missing).\r\n */\r\nexport async function uploadSourceMaps(\r\n options: UploadSourceMapsOptions = {},\r\n): Promise<UploadResult> {\r\n const apiKey =\r\n options.apiKey ||\r\n process.env.BUGSTACK_PROJECT_API_KEY ||\r\n process.env.BUGSTACK_API_KEY;\r\n const endpoint = resolveEndpoint(options.endpoint);\r\n const release = resolveRelease(options.release);\r\n const serverDir = options.serverDir || DEFAULT_SERVER_DIR;\r\n const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);\r\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\r\n const log = options.log || ((m: string) => console.log(m));\r\n const warn = options.warn || ((m: string) => console.warn(m));\r\n\r\n if (!apiKey) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly.\",\r\n );\r\n }\r\n if (!endpoint) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly.\",\r\n );\r\n }\r\n\r\n const start = Date.now();\r\n const mapFiles = await walk(serverDir);\r\n\r\n if (mapFiles.length === 0) {\r\n log(\r\n `[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`,\r\n );\r\n return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };\r\n }\r\n\r\n log(\r\n `[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || \"none\"})...`,\r\n );\r\n\r\n const results = await pool(mapFiles, concurrency, async (mapPath) => {\r\n const bundleFile = bundleFileFor(mapPath, serverDir);\r\n const stats = await stat(mapPath);\r\n if (stats.size > maxBytes) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: true,\r\n error: `Skipped — ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`,\r\n };\r\n }\r\n const mapJson = await readFile(mapPath, \"utf8\");\r\n try {\r\n const res = await fetch(endpoint, {\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n \"X-BugStack-API-Key\": apiKey,\r\n },\r\n body: JSON.stringify({ bundleFile, mapJson, release }),\r\n });\r\n if (!res.ok) {\r\n const text = await res.text().catch(() => \"\");\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: `HTTP ${res.status} ${text.slice(0, 200)}`,\r\n };\r\n }\r\n return { ok: true as const, bundleFile, bytes: stats.size, skipped: false };\r\n } catch (err) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: err instanceof Error ? err.message : String(err),\r\n };\r\n }\r\n });\r\n\r\n const uploaded = results.filter((r) => r.ok).length;\r\n const skipped = results.filter((r) => !r.ok && r.skipped).length;\r\n const failed = results.length - uploaded - skipped;\r\n const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);\r\n const failures = results\r\n .filter((r): r is Extract<typeof r, { ok: false }> => !r.ok && !r.skipped)\r\n .map((r) => ({ bundleFile: r.bundleFile, error: r.error }));\r\n const elapsedMs = Date.now() - start;\r\n\r\n log(\r\n `[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(\r\n 1,\r\n )}MB) in ${(elapsedMs / 1000).toFixed(1)}s.`,\r\n );\r\n if (skipped > 0) {\r\n warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);\r\n }\r\n if (failures.length > 0) {\r\n warn(`[bugstack] ${failures.length} upload(s) failed:`);\r\n for (const f of failures.slice(0, 10)) {\r\n warn(` - ${f.bundleFile}: ${f.error}`);\r\n }\r\n if (failures.length > 10) {\r\n warn(` …and ${failures.length - 10} more`);\r\n }\r\n }\r\n\r\n return { uploaded, skipped, failed, totalBytes, elapsedMs, failures };\r\n}\r\n","/**\r\n * `bugstack` CLI entry point.\r\n *\r\n * One command for now — `bugstack sourcemaps upload` — but the dispatch\r\n * is structured so additional subcommands can land without a breaking\r\n * change. Reads config from flags first, env vars second; everything has\r\n * a sensible default so the typical CI invocation is just:\r\n *\r\n * bugstack sourcemaps upload\r\n */\r\n\r\nimport { parseArgs } from \"node:util\";\r\nimport { uploadSourceMaps, type UploadSourceMapsOptions } from \"./upload\";\r\n\r\nfunction printHelp(): void {\r\n console.log(`bugstack — source-map upload + maintenance CLI\r\n\r\nUSAGE\r\n bugstack sourcemaps upload [options]\r\n bugstack --help\r\n\r\nOPTIONS (sourcemaps upload)\r\n --api-key <key> Project SDK key. Default: BUGSTACK_PROJECT_API_KEY env.\r\n --endpoint <url> Base URL of the bugstack ingest service. Default:\r\n BUGSTACK_ENDPOINT env, or ERROR_SERVICE_URL.\r\n --release <id> Release identifier (commit SHA / version). Default:\r\n BUGSTACK_RELEASE env, RENDER_GIT_COMMIT,\r\n VERCEL_GIT_COMMIT_SHA, GITHUB_SHA, or git rev-parse HEAD.\r\n --server-dir <path> Directory to walk for .map files. Default: .next/server.\r\n --concurrency <n> Max concurrent uploads. Default: 6.\r\n --max-bytes <n> Per-file size cap in bytes. Default: 8388608 (8 MiB).\r\n --quiet Suppress info logs (warnings still printed).\r\n\r\nEXIT CODES\r\n 0 Always — upload failures are reported but never fail the build by\r\n design. Source maps are an optimisation, not a release gate.\r\n`);\r\n}\r\n\r\nasync function runSourceMapsUpload(argv: string[]): Promise<number> {\r\n let parsed;\r\n try {\r\n parsed = parseArgs({\r\n args: argv,\r\n options: {\r\n \"api-key\": { type: \"string\" },\r\n endpoint: { type: \"string\" },\r\n release: { type: \"string\" },\r\n \"server-dir\": { type: \"string\" },\r\n concurrency: { type: \"string\" },\r\n \"max-bytes\": { type: \"string\" },\r\n quiet: { type: \"boolean\", default: false },\r\n help: { type: \"boolean\", short: \"h\", default: false },\r\n },\r\n strict: true,\r\n });\r\n } catch (err) {\r\n console.error(`bugstack: ${(err as Error).message}`);\r\n return 2;\r\n }\r\n\r\n if (parsed.values.help) {\r\n printHelp();\r\n return 0;\r\n }\r\n\r\n const opts: UploadSourceMapsOptions = {\r\n apiKey: parsed.values[\"api-key\"],\r\n endpoint: parsed.values.endpoint,\r\n release: parsed.values.release,\r\n serverDir: parsed.values[\"server-dir\"],\r\n concurrency: parsed.values.concurrency ? Number(parsed.values.concurrency) : undefined,\r\n maxBytes: parsed.values[\"max-bytes\"] ? Number(parsed.values[\"max-bytes\"]) : undefined,\r\n };\r\n if (parsed.values.quiet) {\r\n opts.log = () => {};\r\n }\r\n\r\n try {\r\n await uploadSourceMaps(opts);\r\n return 0;\r\n } catch (err) {\r\n // Distinguish hard config errors (missing key, bad endpoint) from per-\r\n // file failures: only the former should surface as a non-zero exit.\r\n // Per-file failures stay inside uploadSourceMaps and resolve with a\r\n // logged summary.\r\n console.warn(\r\n `[bugstack] Skipping source-map upload: ${err instanceof Error ? err.message : String(err)}`,\r\n );\r\n console.warn(`[bugstack] (This is a soft skip — your build will still succeed.)`);\r\n return 0;\r\n }\r\n}\r\n\r\nasync function main(): Promise<number> {\r\n const [, , command, subcommand, ...rest] = process.argv;\r\n\r\n if (!command || command === \"--help\" || command === \"-h\" || command === \"help\") {\r\n printHelp();\r\n return 0;\r\n }\r\n\r\n if (command === \"sourcemaps\" && subcommand === \"upload\") {\r\n return runSourceMapsUpload(rest);\r\n }\r\n\r\n console.error(`bugstack: unknown command \"${[command, subcommand].filter(Boolean).join(\" \")}\"`);\r\n printHelp();\r\n return 2;\r\n}\r\n\r\nmain().then(\r\n (code) => process.exit(code),\r\n (err) => {\r\n console.error(`bugstack: unexpected error — ${err instanceof Error ? err.stack : err}`);\r\n process.exit(1);\r\n },\r\n);\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/build/upload.ts","../../src/build/cli.ts"],"names":[],"mappings":";;;;;;AAiFA,IAAM,kBAAA,GAAqB,cAAA;AAC3B,IAAM,mBAAA,GAAsB,CAAA;AAC5B,IAAM,iBAAA,GAAoB,IAAI,IAAA,GAAO,IAAA;AACrC,IAAM,aAAA,GAAgB,wBAAA;AAEtB,SAAS,eAAe,QAAA,EAAyC;AAC/D,EAAA,IAAI,QAAA,KAAa,QAAW,OAAO,QAAA;AACnC,EAAA,MAAM,OAAA,GACJ,OAAA,CAAQ,GAAA,CAAI,gBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,iBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,qBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,UAAA;AACd,EAAA,IAAI,SAAS,OAAO,OAAA;AACpB,EAAA,IAAI;AACF,IAAA,OAAO,QAAA,CAAS,oBAAA,EAAsB,EAAE,KAAA,EAAO,CAAC,QAAA,EAAU,MAAA,EAAQ,QAAQ,CAAA,EAAG,CAAA,CAC1E,QAAA,GACA,IAAA,EAAK;AAAA,EACV,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAEA,SAAS,gBAAgB,QAAA,EAAkC;AACzD,EAAA,MAAM,IAAA,GACJ,QAAA,IACA,OAAA,CAAQ,GAAA,CAAI,iBAAA,KACX,QAAQ,GAAA,CAAI,iBAAA,GAAoB,OAAA,CAAQ,GAAA,CAAI,iBAAA,GAAoB,IAAA,CAAA;AACnE,EAAA,IAAI,CAAC,MAAM,OAAO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AAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,KAC5F;AACA,IAAA,OAAA,CAAQ,KAAK,CAAA,sEAAA,CAAmE,CAAA;AAChF,IAAA,OAAO,CAAA;AAAA,EACT;AACF;AAEA,eAAe,IAAA,GAAwB;AACrC,EAAA,MAAM,KAAK,OAAA,EAAS,YAAY,GAAG,IAAI,IAAI,OAAA,CAAQ,IAAA;AAEnD,EAAA,IAAI,CAAC,OAAA,IAAW,OAAA,KAAY,YAAY,OAAA,KAAY,IAAA,IAAQ,YAAY,MAAA,EAAQ;AAC9E,IAAA,SAAA,EAAU;AACV,IAAA,OAAO,CAAA;AAAA,EACT;AAEA,EAAA,IAAI,OAAA,KAAY,YAAA,IAAgB,UAAA,KAAe,QAAA,EAAU;AACvD,IAAA,OAAO,oBAAoB,IAAI,CAAA;AAAA,EACjC;AAEA,EAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,2BAAA,EAA8B,CAAC,OAAA,EAAS,UAAU,CAAA,CAAE,MAAA,CAAO,OAAO,CAAA,CAAE,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,CAAG,CAAA;AAC9F,EAAA,SAAA,EAAU;AACV,EAAA,OAAO,CAAA;AACT;AAEA,IAAA,EAAK,CAAE,IAAA;AAAA,EACL,CAAC,IAAA,KAAS,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAA;AAAA,EAC3B,CAAC,GAAA,KAAQ;AACP,IAAA,OAAA,CAAQ,MAAM,CAAA,kCAAA,EAAgC,GAAA,YAAe,QAAQ,GAAA,CAAI,KAAA,GAAQ,GAAG,CAAA,CAAE,CAAA;AACtF,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF,CAAA","file":"cli.mjs","sourcesContent":["/**\n * Build-time source map uploader.\n *\n * Walks a directory of compiled output looking for `.map` files and POSTs\n * each one to the bugstack source-map ingest endpoint. The companion\n * `bugstack-sdk/next-config` wrapper enables emission of these maps for\n * Next.js server bundles; once uploaded, the orchestrator can resolve\n * production stack frames like \".next/server/chunks/8393.js:1:8734\" back\n * to source-file positions (\"app/api/orders/route.ts:42:5\") and actually\n * generate fixes for bundled errors.\n *\n * This module is import-safe in any Node 18+ environment. It uses no\n * runtime dependencies — `node:fs/promises` + global `fetch`.\n */\n\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join, relative, sep } from \"node:path\";\nimport { execSync } from \"node:child_process\";\n\nexport interface UploadSourceMapsOptions {\n /**\n * Project SDK key. Required. Reads BUGSTACK_PROJECT_API_KEY or\n * BUGSTACK_API_KEY when not supplied explicitly.\n */\n apiKey?: string;\n\n /**\n * Base URL of the bugstack ingest service. Reads BUGSTACK_ENDPOINT or\n * derives from ERROR_SERVICE_URL when not supplied. The uploader appends\n * `/api/sourcemaps/upload` to whatever base it gets.\n */\n endpoint?: string;\n\n /**\n * Release identifier (typically a commit SHA). Lets multiple deploys\n * coexist in the source-map table so old errors still resolve against\n * old maps. Auto-detected in this order:\n * 1. BUGSTACK_RELEASE\n * 2. RENDER_GIT_COMMIT\n * 3. VERCEL_GIT_COMMIT_SHA\n * 4. GITHUB_SHA\n * 5. `git rev-parse HEAD` (when a git checkout is present)\n */\n release?: string | null;\n\n /**\n * Directory to walk for `.map` files. Defaults to `.next/server`.\n * Override for non-Next projects (e.g. `dist` for tsc, `build` for CRA).\n */\n serverDir?: string;\n\n /**\n * Max concurrent uploads. Higher means faster builds, more pressure on\n * the ingest endpoint. Default 6 — tuned for Render's typical bandwidth.\n */\n concurrency?: number;\n\n /**\n * Per-file size cap in bytes. Maps larger than this are skipped with a\n * warning rather than failing. Default 8 MiB — covers typical\n * `.next/server/chunks/*.js.map` outputs comfortably.\n */\n maxBytes?: number;\n\n /**\n * Logger. Defaults to console. Pass a no-op logger to silence the\n * \"[bugstack] …\" lines in scripted environments.\n */\n log?: (message: string) => void;\n warn?: (message: string) => void;\n}\n\nexport interface UploadResult {\n uploaded: number;\n skipped: number;\n failed: number;\n totalBytes: number;\n elapsedMs: number;\n failures: Array<{ bundleFile: string; error: string }>;\n}\n\nconst DEFAULT_SERVER_DIR = \".next/server\";\nconst DEFAULT_CONCURRENCY = 6;\nconst DEFAULT_MAX_BYTES = 8 * 1024 * 1024;\nconst ENDPOINT_PATH = \"/api/sourcemaps/upload\";\n\nfunction resolveRelease(explicit?: string | null): string | null {\n if (explicit !== undefined) return explicit;\n const fromEnv =\n process.env.BUGSTACK_RELEASE ||\n process.env.RENDER_GIT_COMMIT ||\n process.env.VERCEL_GIT_COMMIT_SHA ||\n process.env.GITHUB_SHA;\n if (fromEnv) return fromEnv;\n try {\n return execSync(\"git rev-parse HEAD\", { stdio: [\"ignore\", \"pipe\", \"ignore\"] })\n .toString()\n .trim();\n } catch {\n return null;\n }\n}\n\nfunction resolveEndpoint(explicit?: string): string | null {\n const base =\n explicit ||\n process.env.BUGSTACK_ENDPOINT ||\n (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);\n if (!base) return null;\n // Strip trailing slashes + any trailing /api/capture or /capture so the\n // same env var that points the SDK at ingestion also works for sourcemaps.\n const normalised = base\n .replace(/\\/+$/, \"\")\n .replace(/\\/api\\/capture$/, \"\")\n .replace(/\\/capture$/, \"\");\n return normalised + ENDPOINT_PATH;\n}\n\nasync function walk(dir: string): Promise<string[]> {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n const out: string[] = [];\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n out.push(...(await walk(path)));\n } else if (entry.name.endsWith(\".map\")) {\n out.push(path);\n }\n }\n return out;\n}\n\nasync function pool<T, R>(\n items: T[],\n workers: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let i = 0;\n const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {\n while (i < items.length) {\n const idx = i++;\n results[idx] = await fn(items[idx]);\n }\n });\n await Promise.all(runners);\n return results;\n}\n\nfunction bundleFileFor(mapPath: string, serverDir: string): string {\n // Strip the serverDir prefix and the .map suffix; normalise Windows\n // backslashes so the bundleFile key stored on the server is portable\n // regardless of where the build ran.\n return relative(serverDir, mapPath)\n .replace(/\\.map$/, \"\")\n .split(sep)\n .join(\"/\");\n}\n\n/**\n * Upload every `.map` file under `serverDir` to the bugstack source-map\n * endpoint. Tolerant: never throws on individual file failures, returns\n * a summary the caller can decide what to do with.\n *\n * Throws only on hard configuration errors (no API key, no resolvable\n * endpoint, serverDir totally missing).\n */\nexport async function uploadSourceMaps(\n options: UploadSourceMapsOptions = {},\n): Promise<UploadResult> {\n const apiKey =\n options.apiKey ||\n process.env.BUGSTACK_PROJECT_API_KEY ||\n process.env.BUGSTACK_API_KEY;\n const endpoint = resolveEndpoint(options.endpoint);\n const release = resolveRelease(options.release);\n const serverDir = options.serverDir || DEFAULT_SERVER_DIR;\n const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n const log = options.log || ((m: string) => console.log(m));\n const warn = options.warn || ((m: string) => console.warn(m));\n\n if (!apiKey) {\n throw new Error(\n \"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly.\",\n );\n }\n if (!endpoint) {\n throw new Error(\n \"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly.\",\n );\n }\n\n const start = Date.now();\n const mapFiles = await walk(serverDir);\n\n if (mapFiles.length === 0) {\n log(\n `[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`,\n );\n return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };\n }\n\n log(\n `[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || \"none\"})...`,\n );\n\n const results = await pool(mapFiles, concurrency, async (mapPath) => {\n const bundleFile = bundleFileFor(mapPath, serverDir);\n const stats = await stat(mapPath);\n if (stats.size > maxBytes) {\n return {\n ok: false as const,\n bundleFile,\n bytes: 0,\n skipped: true,\n error: `Skipped — ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`,\n };\n }\n const mapJson = await readFile(mapPath, \"utf8\");\n try {\n const res = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-BugStack-API-Key\": apiKey,\n },\n body: JSON.stringify({ bundleFile, mapJson, release }),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n return {\n ok: false as const,\n bundleFile,\n bytes: 0,\n skipped: false,\n error: `HTTP ${res.status} ${text.slice(0, 200)}`,\n };\n }\n return { ok: true as const, bundleFile, bytes: stats.size, skipped: false };\n } catch (err) {\n return {\n ok: false as const,\n bundleFile,\n bytes: 0,\n skipped: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n });\n\n const uploaded = results.filter((r) => r.ok).length;\n const skipped = results.filter((r) => !r.ok && r.skipped).length;\n const failed = results.length - uploaded - skipped;\n const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);\n const failures = results\n .filter((r): r is Extract<typeof r, { ok: false }> => !r.ok && !r.skipped)\n .map((r) => ({ bundleFile: r.bundleFile, error: r.error }));\n const elapsedMs = Date.now() - start;\n\n log(\n `[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(\n 1,\n )}MB) in ${(elapsedMs / 1000).toFixed(1)}s.`,\n );\n if (skipped > 0) {\n warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);\n }\n if (failures.length > 0) {\n warn(`[bugstack] ${failures.length} upload(s) failed:`);\n for (const f of failures.slice(0, 10)) {\n warn(` - ${f.bundleFile}: ${f.error}`);\n }\n if (failures.length > 10) {\n warn(` …and ${failures.length - 10} more`);\n }\n }\n\n return { uploaded, skipped, failed, totalBytes, elapsedMs, failures };\n}\n","/**\n * `bugstack` CLI entry point.\n *\n * One command for now — `bugstack sourcemaps upload` — but the dispatch\n * is structured so additional subcommands can land without a breaking\n * change. Reads config from flags first, env vars second; everything has\n * a sensible default so the typical CI invocation is just:\n *\n * bugstack sourcemaps upload\n */\n\nimport { parseArgs } from \"node:util\";\nimport { uploadSourceMaps, type UploadSourceMapsOptions } from \"./upload\";\n\nfunction printHelp(): void {\n console.log(`bugstack — source-map upload + maintenance CLI\n\nUSAGE\n bugstack sourcemaps upload [options]\n bugstack --help\n\nOPTIONS (sourcemaps upload)\n --api-key <key> Project SDK key. Default: BUGSTACK_PROJECT_API_KEY env.\n --endpoint <url> Base URL of the bugstack ingest service. Default:\n BUGSTACK_ENDPOINT env, or ERROR_SERVICE_URL.\n --release <id> Release identifier (commit SHA / version). Default:\n BUGSTACK_RELEASE env, RENDER_GIT_COMMIT,\n VERCEL_GIT_COMMIT_SHA, GITHUB_SHA, or git rev-parse HEAD.\n --server-dir <path> Directory to walk for .map files. Default: .next/server.\n --concurrency <n> Max concurrent uploads. Default: 6.\n --max-bytes <n> Per-file size cap in bytes. Default: 8388608 (8 MiB).\n --quiet Suppress info logs (warnings still printed).\n\nEXIT CODES\n 0 Always — upload failures are reported but never fail the build by\n design. Source maps are an optimisation, not a release gate.\n`);\n}\n\nasync function runSourceMapsUpload(argv: string[]): Promise<number> {\n let parsed;\n try {\n parsed = parseArgs({\n args: argv,\n options: {\n \"api-key\": { type: \"string\" },\n endpoint: { type: \"string\" },\n release: { type: \"string\" },\n \"server-dir\": { type: \"string\" },\n concurrency: { type: \"string\" },\n \"max-bytes\": { type: \"string\" },\n quiet: { type: \"boolean\", default: false },\n help: { type: \"boolean\", short: \"h\", default: false },\n },\n strict: true,\n });\n } catch (err) {\n console.error(`bugstack: ${(err as Error).message}`);\n return 2;\n }\n\n if (parsed.values.help) {\n printHelp();\n return 0;\n }\n\n const opts: UploadSourceMapsOptions = {\n apiKey: parsed.values[\"api-key\"],\n endpoint: parsed.values.endpoint,\n release: parsed.values.release,\n serverDir: parsed.values[\"server-dir\"],\n concurrency: parsed.values.concurrency ? Number(parsed.values.concurrency) : undefined,\n maxBytes: parsed.values[\"max-bytes\"] ? Number(parsed.values[\"max-bytes\"]) : undefined,\n };\n if (parsed.values.quiet) {\n opts.log = () => {};\n }\n\n try {\n await uploadSourceMaps(opts);\n return 0;\n } catch (err) {\n // Distinguish hard config errors (missing key, bad endpoint) from per-\n // file failures: only the former should surface as a non-zero exit.\n // Per-file failures stay inside uploadSourceMaps and resolve with a\n // logged summary.\n console.warn(\n `[bugstack] Skipping source-map upload: ${err instanceof Error ? err.message : String(err)}`,\n );\n console.warn(`[bugstack] (This is a soft skip — your build will still succeed.)`);\n return 0;\n }\n}\n\nasync function main(): Promise<number> {\n const [, , command, subcommand, ...rest] = process.argv;\n\n if (!command || command === \"--help\" || command === \"-h\" || command === \"help\") {\n printHelp();\n return 0;\n }\n\n if (command === \"sourcemaps\" && subcommand === \"upload\") {\n return runSourceMapsUpload(rest);\n }\n\n console.error(`bugstack: unknown command \"${[command, subcommand].filter(Boolean).join(\" \")}\"`);\n printHelp();\n return 2;\n}\n\nmain().then(\n (code) => process.exit(code),\n (err) => {\n console.error(`bugstack: unexpected error — ${err instanceof Error ? err.stack : err}`);\n process.exit(1);\n },\n);\n"]}
|
package/dist/build/upload.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/build/upload.ts"],"names":["execSync","readdir","path","join","relative","sep","stat","readFile"],"mappings":";;;;;;;AAiFA,IAAM,kBAAA,GAAqB,cAAA;AAC3B,IAAM,mBAAA,GAAsB,CAAA;AAC5B,IAAM,iBAAA,GAAoB,IAAI,IAAA,GAAO,IAAA;AACrC,IAAM,aAAA,GAAgB,wBAAA;AAEtB,SAAS,eAAe,QAAA,EAAyC;AAC/D,EAAA,IAAI,QAAA,KAAa,QAAW,OAAO,QAAA;AACnC,EAAA,MAAM,OAAA,GACJ,O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` files and POSTs\r\n * each one to the bugstack source-map ingest endpoint. The companion\r\n * `bugstack-sdk/next-config` wrapper enables emission of these maps for\r\n * Next.js server bundles; once uploaded, the orchestrator can resolve\r\n * production stack frames like \".next/server/chunks/8393.js:1:8734\" back\r\n * to source-file positions (\"app/api/orders/route.ts:42:5\") and actually\r\n * generate fixes for bundled errors.\r\n *\r\n * This module is import-safe in any Node 18+ environment. It uses no\r\n * runtime dependencies — `node:fs/promises` + global `fetch`.\r\n */\r\n\r\nimport { readdir, readFile, stat } from \"node:fs/promises\";\r\nimport { join, relative, sep } from \"node:path\";\r\nimport { execSync } from \"node:child_process\";\r\n\r\nexport interface UploadSourceMapsOptions {\r\n /**\r\n * Project SDK key. Required. Reads BUGSTACK_PROJECT_API_KEY or\r\n * BUGSTACK_API_KEY when not supplied explicitly.\r\n */\r\n apiKey?: string;\r\n\r\n /**\r\n * Base URL of the bugstack ingest service. Reads BUGSTACK_ENDPOINT or\r\n * derives from ERROR_SERVICE_URL when not supplied. The uploader appends\r\n * `/api/sourcemaps/upload` to whatever base it gets.\r\n */\r\n endpoint?: string;\r\n\r\n /**\r\n * Release identifier (typically a commit SHA). Lets multiple deploys\r\n * coexist in the source-map table so old errors still resolve against\r\n * old maps. Auto-detected in this order:\r\n * 1. BUGSTACK_RELEASE\r\n * 2. RENDER_GIT_COMMIT\r\n * 3. VERCEL_GIT_COMMIT_SHA\r\n * 4. GITHUB_SHA\r\n * 5. `git rev-parse HEAD` (when a git checkout is present)\r\n */\r\n release?: string | null;\r\n\r\n /**\r\n * Directory to walk for `.map` files. Defaults to `.next/server`.\r\n * Override for non-Next projects (e.g. `dist` for tsc, `build` for CRA).\r\n */\r\n serverDir?: string;\r\n\r\n /**\r\n * Max concurrent uploads. Higher means faster builds, more pressure on\r\n * the ingest endpoint. Default 6 — tuned for Render's typical bandwidth.\r\n */\r\n concurrency?: number;\r\n\r\n /**\r\n * Per-file size cap in bytes. Maps larger than this are skipped with a\r\n * warning rather than failing. Default 8 MiB — covers typical\r\n * `.next/server/chunks/*.js.map` outputs comfortably.\r\n */\r\n maxBytes?: number;\r\n\r\n /**\r\n * Logger. Defaults to console. Pass a no-op logger to silence the\r\n * \"[bugstack] …\" lines in scripted environments.\r\n */\r\n log?: (message: string) => void;\r\n warn?: (message: string) => void;\r\n}\r\n\r\nexport interface UploadResult {\r\n uploaded: number;\r\n skipped: number;\r\n failed: number;\r\n totalBytes: number;\r\n elapsedMs: number;\r\n failures: Array<{ bundleFile: string; error: string }>;\r\n}\r\n\r\nconst DEFAULT_SERVER_DIR = \".next/server\";\r\nconst DEFAULT_CONCURRENCY = 6;\r\nconst DEFAULT_MAX_BYTES = 8 * 1024 * 1024;\r\nconst ENDPOINT_PATH = \"/api/sourcemaps/upload\";\r\n\r\nfunction resolveRelease(explicit?: string | null): string | null {\r\n if (explicit !== undefined) return explicit;\r\n const fromEnv =\r\n process.env.BUGSTACK_RELEASE ||\r\n process.env.RENDER_GIT_COMMIT ||\r\n process.env.VERCEL_GIT_COMMIT_SHA ||\r\n process.env.GITHUB_SHA;\r\n if (fromEnv) return fromEnv;\r\n try {\r\n return execSync(\"git rev-parse HEAD\", { stdio: [\"ignore\", \"pipe\", \"ignore\"] })\r\n .toString()\r\n .trim();\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nfunction resolveEndpoint(explicit?: string): string | null {\r\n const base =\r\n explicit ||\r\n process.env.BUGSTACK_ENDPOINT ||\r\n (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);\r\n if (!base) return null;\r\n // Strip trailing slashes + any trailing /api/capture or /capture so the\r\n // same env var that points the SDK at ingestion also works for sourcemaps.\r\n const normalised = base\r\n .replace(/\\/+$/, \"\")\r\n .replace(/\\/api\\/capture$/, \"\")\r\n .replace(/\\/capture$/, \"\");\r\n return normalised + ENDPOINT_PATH;\r\n}\r\n\r\nasync function walk(dir: string): Promise<string[]> {\r\n let entries;\r\n try {\r\n entries = await readdir(dir, { withFileTypes: true });\r\n } catch (err) {\r\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\r\n throw err;\r\n }\r\n const out: string[] = [];\r\n for (const entry of entries) {\r\n const path = join(dir, entry.name);\r\n if (entry.isDirectory()) {\r\n out.push(...(await walk(path)));\r\n } else if (entry.name.endsWith(\".map\")) {\r\n out.push(path);\r\n }\r\n }\r\n return out;\r\n}\r\n\r\nasync function pool<T, R>(\r\n items: T[],\r\n workers: number,\r\n fn: (item: T) => Promise<R>,\r\n): Promise<R[]> {\r\n const results: R[] = new Array(items.length);\r\n let i = 0;\r\n const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {\r\n while (i < items.length) {\r\n const idx = i++;\r\n results[idx] = await fn(items[idx]);\r\n }\r\n });\r\n await Promise.all(runners);\r\n return results;\r\n}\r\n\r\nfunction bundleFileFor(mapPath: string, serverDir: string): string {\r\n // Strip the serverDir prefix and the .map suffix; normalise Windows\r\n // backslashes so the bundleFile key stored on the server is portable\r\n // regardless of where the build ran.\r\n return relative(serverDir, mapPath)\r\n .replace(/\\.map$/, \"\")\r\n .split(sep)\r\n .join(\"/\");\r\n}\r\n\r\n/**\r\n * Upload every `.map` file under `serverDir` to the bugstack source-map\r\n * endpoint. Tolerant: never throws on individual file failures, returns\r\n * a summary the caller can decide what to do with.\r\n *\r\n * Throws only on hard configuration errors (no API key, no resolvable\r\n * endpoint, serverDir totally missing).\r\n */\r\nexport async function uploadSourceMaps(\r\n options: UploadSourceMapsOptions = {},\r\n): Promise<UploadResult> {\r\n const apiKey =\r\n options.apiKey ||\r\n process.env.BUGSTACK_PROJECT_API_KEY ||\r\n process.env.BUGSTACK_API_KEY;\r\n const endpoint = resolveEndpoint(options.endpoint);\r\n const release = resolveRelease(options.release);\r\n const serverDir = options.serverDir || DEFAULT_SERVER_DIR;\r\n const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);\r\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\r\n const log = options.log || ((m: string) => console.log(m));\r\n const warn = options.warn || ((m: string) => console.warn(m));\r\n\r\n if (!apiKey) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly.\",\r\n );\r\n }\r\n if (!endpoint) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly.\",\r\n );\r\n }\r\n\r\n const start = Date.now();\r\n const mapFiles = await walk(serverDir);\r\n\r\n if (mapFiles.length === 0) {\r\n log(\r\n `[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`,\r\n );\r\n return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };\r\n }\r\n\r\n log(\r\n `[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || \"none\"})...`,\r\n );\r\n\r\n const results = await pool(mapFiles, concurrency, async (mapPath) => {\r\n const bundleFile = bundleFileFor(mapPath, serverDir);\r\n const stats = await stat(mapPath);\r\n if (stats.size > maxBytes) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: true,\r\n error: `Skipped — ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`,\r\n };\r\n }\r\n const mapJson = await readFile(mapPath, \"utf8\");\r\n try {\r\n const res = await fetch(endpoint, {\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n \"X-BugStack-API-Key\": apiKey,\r\n },\r\n body: JSON.stringify({ bundleFile, mapJson, release }),\r\n });\r\n if (!res.ok) {\r\n const text = await res.text().catch(() => \"\");\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: `HTTP ${res.status} ${text.slice(0, 200)}`,\r\n };\r\n }\r\n return { ok: true as const, bundleFile, bytes: stats.size, skipped: false };\r\n } catch (err) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: err instanceof Error ? err.message : String(err),\r\n };\r\n }\r\n });\r\n\r\n const uploaded = results.filter((r) => r.ok).length;\r\n const skipped = results.filter((r) => !r.ok && r.skipped).length;\r\n const failed = results.length - uploaded - skipped;\r\n const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);\r\n const failures = results\r\n .filter((r): r is Extract<typeof r, { ok: false }> => !r.ok && !r.skipped)\r\n .map((r) => ({ bundleFile: r.bundleFile, error: r.error }));\r\n const elapsedMs = Date.now() - start;\r\n\r\n log(\r\n `[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(\r\n 1,\r\n )}MB) in ${(elapsedMs / 1000).toFixed(1)}s.`,\r\n );\r\n if (skipped > 0) {\r\n warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);\r\n }\r\n if (failures.length > 0) {\r\n warn(`[bugstack] ${failures.length} upload(s) failed:`);\r\n for (const f of failures.slice(0, 10)) {\r\n warn(` - ${f.bundleFile}: ${f.error}`);\r\n }\r\n if (failures.length > 10) {\r\n warn(` …and ${failures.length - 10} more`);\r\n }\r\n }\r\n\r\n return { uploaded, skipped, failed, totalBytes, elapsedMs, failures };\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/build/upload.ts"],"names":["execSync","readdir","path","join","relative","sep","stat","readFile"],"mappings":";;;;;;;AAiFA,IAAM,kBAAA,GAAqB,cAAA;AAC3B,IAAM,mBAAA,GAAsB,CAAA;AAC5B,IAAM,iBAAA,GAAoB,IAAI,IAAA,GAAO,IAAA;AACrC,IAAM,aAAA,GAAgB,wBAAA;AAEtB,SAAS,eAAe,QAAA,EAAyC;AAC/D,EAAA,IAAI,QAAA,KAAa,QAAW,OAAO,QAAA;AACnC,EAAA,MAAM,OAAA,GACJ,OAAA,CAAQ,GAAA,CAAI,gBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,iBA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KAAA,EAAM,CAAE,CAAA;AAC5D,EAAA,MAAM,SAAA,GAAY,IAAA,CAAK,GAAA,EAAI,GAAI,KAAA;AAE/B,EAAA,GAAA;AAAA,IACE,CAAA,oBAAA,EAAuB,QAAQ,CAAA,CAAA,EAAI,OAAA,CAAQ,MAAM,CAAA,OAAA,EAAA,CAAW,UAAA,GAAa,OAAO,IAAA,EAAM,OAAA;AAAA,MACpF;AAAA,KACD,CAAA,OAAA,EAAA,CAAW,SAAA,GAAY,GAAA,EAAM,OAAA,CAAQ,CAAC,CAAC,CAAA,EAAA;AAAA,GAC1C;AACA,EAAA,IAAI,UAAU,CAAA,EAAG;AACf,IAAA,IAAA,CAAK,CAAA,mBAAA,EAAsB,OAAO,CAAA,0BAAA,CAA4B,CAAA;AAAA,EAChE;AACA,EAAA,IAAI,QAAA,CAAS,SAAS,CAAA,EAAG;AACvB,IAAA,IAAA,CAAK,CAAA,WAAA,EAAc,QAAA,CAAS,MAAM,CAAA,kBAAA,CAAoB,CAAA;AACtD,IAAA,KAAA,MAAW,CAAA,IAAK,QAAA,CAAS,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,EAAG;AACrC,MAAA,IAAA,CAAK,OAAO,CAAA,CAAE,UAAU,CAAA,EAAA,EAAK,CAAA,CAAE,KAAK,CAAA,CAAE,CAAA;AAAA,IACxC;AACA,IAAA,IAAI,QAAA,CAAS,SAAS,EAAA,EAAI;AACxB,MAAA,IAAA,CAAK,CAAA,YAAA,EAAU,QAAA,CAAS,MAAA,GAAS,EAAE,CAAA,KAAA,CAAO,CAAA;AAAA,IAC5C;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,MAAA,EAAQ,UAAA,EAAY,WAAW,QAAA,EAAS;AACtE","file":"upload.js","sourcesContent":["/**\n * Build-time source map uploader.\n *\n * Walks a directory of compiled output looking for `.map` files and POSTs\n * each one to the bugstack source-map ingest endpoint. The companion\n * `bugstack-sdk/next-config` wrapper enables emission of these maps for\n * Next.js server bundles; once uploaded, the orchestrator can resolve\n * production stack frames like \".next/server/chunks/8393.js:1:8734\" back\n * to source-file positions (\"app/api/orders/route.ts:42:5\") and actually\n * generate fixes for bundled errors.\n *\n * This module is import-safe in any Node 18+ environment. It uses no\n * runtime dependencies — `node:fs/promises` + global `fetch`.\n */\n\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join, relative, sep } from \"node:path\";\nimport { execSync } from \"node:child_process\";\n\nexport interface UploadSourceMapsOptions {\n /**\n * Project SDK key. Required. Reads BUGSTACK_PROJECT_API_KEY or\n * BUGSTACK_API_KEY when not supplied explicitly.\n */\n apiKey?: string;\n\n /**\n * Base URL of the bugstack ingest service. Reads BUGSTACK_ENDPOINT or\n * derives from ERROR_SERVICE_URL when not supplied. The uploader appends\n * `/api/sourcemaps/upload` to whatever base it gets.\n */\n endpoint?: string;\n\n /**\n * Release identifier (typically a commit SHA). Lets multiple deploys\n * coexist in the source-map table so old errors still resolve against\n * old maps. Auto-detected in this order:\n * 1. BUGSTACK_RELEASE\n * 2. RENDER_GIT_COMMIT\n * 3. VERCEL_GIT_COMMIT_SHA\n * 4. GITHUB_SHA\n * 5. `git rev-parse HEAD` (when a git checkout is present)\n */\n release?: string | null;\n\n /**\n * Directory to walk for `.map` files. Defaults to `.next/server`.\n * Override for non-Next projects (e.g. `dist` for tsc, `build` for CRA).\n */\n serverDir?: string;\n\n /**\n * Max concurrent uploads. Higher means faster builds, more pressure on\n * the ingest endpoint. Default 6 — tuned for Render's typical bandwidth.\n */\n concurrency?: number;\n\n /**\n * Per-file size cap in bytes. Maps larger than this are skipped with a\n * warning rather than failing. Default 8 MiB — covers typical\n * `.next/server/chunks/*.js.map` outputs comfortably.\n */\n maxBytes?: number;\n\n /**\n * Logger. Defaults to console. Pass a no-op logger to silence the\n * \"[bugstack] …\" lines in scripted environments.\n */\n log?: (message: string) => void;\n warn?: (message: string) => void;\n}\n\nexport interface UploadResult {\n uploaded: number;\n skipped: number;\n failed: number;\n totalBytes: number;\n elapsedMs: number;\n failures: Array<{ bundleFile: string; error: string }>;\n}\n\nconst DEFAULT_SERVER_DIR = \".next/server\";\nconst DEFAULT_CONCURRENCY = 6;\nconst DEFAULT_MAX_BYTES = 8 * 1024 * 1024;\nconst ENDPOINT_PATH = \"/api/sourcemaps/upload\";\n\nfunction resolveRelease(explicit?: string | null): string | null {\n if (explicit !== undefined) return explicit;\n const fromEnv =\n process.env.BUGSTACK_RELEASE ||\n process.env.RENDER_GIT_COMMIT ||\n process.env.VERCEL_GIT_COMMIT_SHA ||\n process.env.GITHUB_SHA;\n if (fromEnv) return fromEnv;\n try {\n return execSync(\"git rev-parse HEAD\", { stdio: [\"ignore\", \"pipe\", \"ignore\"] })\n .toString()\n .trim();\n } catch {\n return null;\n }\n}\n\nfunction resolveEndpoint(explicit?: string): string | null {\n const base =\n explicit ||\n process.env.BUGSTACK_ENDPOINT ||\n (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);\n if (!base) return null;\n // Strip trailing slashes + any trailing /api/capture or /capture so the\n // same env var that points the SDK at ingestion also works for sourcemaps.\n const normalised = base\n .replace(/\\/+$/, \"\")\n .replace(/\\/api\\/capture$/, \"\")\n .replace(/\\/capture$/, \"\");\n return normalised + ENDPOINT_PATH;\n}\n\nasync function walk(dir: string): Promise<string[]> {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n const out: string[] = [];\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n out.push(...(await walk(path)));\n } else if (entry.name.endsWith(\".map\")) {\n out.push(path);\n }\n }\n return out;\n}\n\nasync function pool<T, R>(\n items: T[],\n workers: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let i = 0;\n const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {\n while (i < items.length) {\n const idx = i++;\n results[idx] = await fn(items[idx]);\n }\n });\n await Promise.all(runners);\n return results;\n}\n\nfunction bundleFileFor(mapPath: string, serverDir: string): string {\n // Strip the serverDir prefix and the .map suffix; normalise Windows\n // backslashes so the bundleFile key stored on the server is portable\n // regardless of where the build ran.\n return relative(serverDir, mapPath)\n .replace(/\\.map$/, \"\")\n .split(sep)\n .join(\"/\");\n}\n\n/**\n * Upload every `.map` file under `serverDir` to the bugstack source-map\n * endpoint. Tolerant: never throws on individual file failures, returns\n * a summary the caller can decide what to do with.\n *\n * Throws only on hard configuration errors (no API key, no resolvable\n * endpoint, serverDir totally missing).\n */\nexport async function uploadSourceMaps(\n options: UploadSourceMapsOptions = {},\n): Promise<UploadResult> {\n const apiKey =\n options.apiKey ||\n process.env.BUGSTACK_PROJECT_API_KEY ||\n process.env.BUGSTACK_API_KEY;\n const endpoint = resolveEndpoint(options.endpoint);\n const release = resolveRelease(options.release);\n const serverDir = options.serverDir || DEFAULT_SERVER_DIR;\n const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n const log = options.log || ((m: string) => console.log(m));\n const warn = options.warn || ((m: string) => console.warn(m));\n\n if (!apiKey) {\n throw new Error(\n \"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly.\",\n );\n }\n if (!endpoint) {\n throw new Error(\n \"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly.\",\n );\n }\n\n const start = Date.now();\n const mapFiles = await walk(serverDir);\n\n if (mapFiles.length === 0) {\n log(\n `[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`,\n );\n return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };\n }\n\n log(\n `[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || \"none\"})...`,\n );\n\n const results = await pool(mapFiles, concurrency, async (mapPath) => {\n const bundleFile = bundleFileFor(mapPath, serverDir);\n const stats = await stat(mapPath);\n if (stats.size > maxBytes) {\n return {\n ok: false as const,\n bundleFile,\n bytes: 0,\n skipped: true,\n error: `Skipped — ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`,\n };\n }\n const mapJson = await readFile(mapPath, \"utf8\");\n try {\n const res = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-BugStack-API-Key\": apiKey,\n },\n body: JSON.stringify({ bundleFile, mapJson, release }),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n return {\n ok: false as const,\n bundleFile,\n bytes: 0,\n skipped: false,\n error: `HTTP ${res.status} ${text.slice(0, 200)}`,\n };\n }\n return { ok: true as const, bundleFile, bytes: stats.size, skipped: false };\n } catch (err) {\n return {\n ok: false as const,\n bundleFile,\n bytes: 0,\n skipped: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n });\n\n const uploaded = results.filter((r) => r.ok).length;\n const skipped = results.filter((r) => !r.ok && r.skipped).length;\n const failed = results.length - uploaded - skipped;\n const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);\n const failures = results\n .filter((r): r is Extract<typeof r, { ok: false }> => !r.ok && !r.skipped)\n .map((r) => ({ bundleFile: r.bundleFile, error: r.error }));\n const elapsedMs = Date.now() - start;\n\n log(\n `[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(\n 1,\n )}MB) in ${(elapsedMs / 1000).toFixed(1)}s.`,\n );\n if (skipped > 0) {\n warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);\n }\n if (failures.length > 0) {\n warn(`[bugstack] ${failures.length} upload(s) failed:`);\n for (const f of failures.slice(0, 10)) {\n warn(` - ${f.bundleFile}: ${f.error}`);\n }\n if (failures.length > 10) {\n warn(` …and ${failures.length - 10} more`);\n }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CAAA,CAAE,KAAK,CAAA,CAAE,CAAA;AAAA,IACxC;AACA,IAAA,IAAI,QAAA,CAAS,SAAS,EAAA,EAAI;AACxB,MAAA,IAAA,CAAK,CAAA,YAAA,EAAU,QAAA,CAAS,MAAA,GAAS,EAAE,CAAA,KAAA,CAAO,CAAA;AAAA,IAC5C;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,MAAA,EAAQ,UAAA,EAAY,WAAW,QAAA,EAAS;AACtE","file":"upload.mjs","sourcesContent":["/**\r\n * Build-time source map uploader.\r\n *\r\n * Walks a directory of compiled output looking for `.map` files and POSTs\r\n * each one to the bugstack source-map ingest endpoint. The companion\r\n * `bugstack-sdk/next-config` wrapper enables emission of these maps for\r\n * Next.js server bundles; once uploaded, the orchestrator can resolve\r\n * production stack frames like \".next/server/chunks/8393.js:1:8734\" back\r\n * to source-file positions (\"app/api/orders/route.ts:42:5\") and actually\r\n * generate fixes for bundled errors.\r\n *\r\n * This module is import-safe in any Node 18+ environment. It uses no\r\n * runtime dependencies — `node:fs/promises` + global `fetch`.\r\n */\r\n\r\nimport { readdir, readFile, stat } from \"node:fs/promises\";\r\nimport { join, relative, sep } from \"node:path\";\r\nimport { execSync } from \"node:child_process\";\r\n\r\nexport interface UploadSourceMapsOptions {\r\n /**\r\n * Project SDK key. Required. Reads BUGSTACK_PROJECT_API_KEY or\r\n * BUGSTACK_API_KEY when not supplied explicitly.\r\n */\r\n apiKey?: string;\r\n\r\n /**\r\n * Base URL of the bugstack ingest service. Reads BUGSTACK_ENDPOINT or\r\n * derives from ERROR_SERVICE_URL when not supplied. The uploader appends\r\n * `/api/sourcemaps/upload` to whatever base it gets.\r\n */\r\n endpoint?: string;\r\n\r\n /**\r\n * Release identifier (typically a commit SHA). Lets multiple deploys\r\n * coexist in the source-map table so old errors still resolve against\r\n * old maps. Auto-detected in this order:\r\n * 1. BUGSTACK_RELEASE\r\n * 2. RENDER_GIT_COMMIT\r\n * 3. VERCEL_GIT_COMMIT_SHA\r\n * 4. GITHUB_SHA\r\n * 5. `git rev-parse HEAD` (when a git checkout is present)\r\n */\r\n release?: string | null;\r\n\r\n /**\r\n * Directory to walk for `.map` files. Defaults to `.next/server`.\r\n * Override for non-Next projects (e.g. `dist` for tsc, `build` for CRA).\r\n */\r\n serverDir?: string;\r\n\r\n /**\r\n * Max concurrent uploads. Higher means faster builds, more pressure on\r\n * the ingest endpoint. Default 6 — tuned for Render's typical bandwidth.\r\n */\r\n concurrency?: number;\r\n\r\n /**\r\n * Per-file size cap in bytes. Maps larger than this are skipped with a\r\n * warning rather than failing. Default 8 MiB — covers typical\r\n * `.next/server/chunks/*.js.map` outputs comfortably.\r\n */\r\n maxBytes?: number;\r\n\r\n /**\r\n * Logger. Defaults to console. Pass a no-op logger to silence the\r\n * \"[bugstack] …\" lines in scripted environments.\r\n */\r\n log?: (message: string) => void;\r\n warn?: (message: string) => void;\r\n}\r\n\r\nexport interface UploadResult {\r\n uploaded: number;\r\n skipped: number;\r\n failed: number;\r\n totalBytes: number;\r\n elapsedMs: number;\r\n failures: Array<{ bundleFile: string; error: string }>;\r\n}\r\n\r\nconst DEFAULT_SERVER_DIR = \".next/server\";\r\nconst DEFAULT_CONCURRENCY = 6;\r\nconst DEFAULT_MAX_BYTES = 8 * 1024 * 1024;\r\nconst ENDPOINT_PATH = \"/api/sourcemaps/upload\";\r\n\r\nfunction resolveRelease(explicit?: string | null): string | null {\r\n if (explicit !== undefined) return explicit;\r\n const fromEnv =\r\n process.env.BUGSTACK_RELEASE ||\r\n process.env.RENDER_GIT_COMMIT ||\r\n process.env.VERCEL_GIT_COMMIT_SHA ||\r\n process.env.GITHUB_SHA;\r\n if (fromEnv) return fromEnv;\r\n try {\r\n return execSync(\"git rev-parse HEAD\", { stdio: [\"ignore\", \"pipe\", \"ignore\"] })\r\n .toString()\r\n .trim();\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nfunction resolveEndpoint(explicit?: string): string | null {\r\n const base =\r\n explicit ||\r\n process.env.BUGSTACK_ENDPOINT ||\r\n (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);\r\n if (!base) return null;\r\n // Strip trailing slashes + any trailing /api/capture or /capture so the\r\n // same env var that points the SDK at ingestion also works for sourcemaps.\r\n const normalised = base\r\n .replace(/\\/+$/, \"\")\r\n .replace(/\\/api\\/capture$/, \"\")\r\n .replace(/\\/capture$/, \"\");\r\n return normalised + ENDPOINT_PATH;\r\n}\r\n\r\nasync function walk(dir: string): Promise<string[]> {\r\n let entries;\r\n try {\r\n entries = await readdir(dir, { withFileTypes: true });\r\n } catch (err) {\r\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\r\n throw err;\r\n }\r\n const out: string[] = [];\r\n for (const entry of entries) {\r\n const path = join(dir, entry.name);\r\n if (entry.isDirectory()) {\r\n out.push(...(await walk(path)));\r\n } else if (entry.name.endsWith(\".map\")) {\r\n out.push(path);\r\n }\r\n }\r\n return out;\r\n}\r\n\r\nasync function pool<T, R>(\r\n items: T[],\r\n workers: number,\r\n fn: (item: T) => Promise<R>,\r\n): Promise<R[]> {\r\n const results: R[] = new Array(items.length);\r\n let i = 0;\r\n const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {\r\n while (i < items.length) {\r\n const idx = i++;\r\n results[idx] = await fn(items[idx]);\r\n }\r\n });\r\n await Promise.all(runners);\r\n return results;\r\n}\r\n\r\nfunction bundleFileFor(mapPath: string, serverDir: string): string {\r\n // Strip the serverDir prefix and the .map suffix; normalise Windows\r\n // backslashes so the bundleFile key stored on the server is portable\r\n // regardless of where the build ran.\r\n return relative(serverDir, mapPath)\r\n .replace(/\\.map$/, \"\")\r\n .split(sep)\r\n .join(\"/\");\r\n}\r\n\r\n/**\r\n * Upload every `.map` file under `serverDir` to the bugstack source-map\r\n * endpoint. Tolerant: never throws on individual file failures, returns\r\n * a summary the caller can decide what to do with.\r\n *\r\n * Throws only on hard configuration errors (no API key, no resolvable\r\n * endpoint, serverDir totally missing).\r\n */\r\nexport async function uploadSourceMaps(\r\n options: UploadSourceMapsOptions = {},\r\n): Promise<UploadResult> {\r\n const apiKey =\r\n options.apiKey ||\r\n process.env.BUGSTACK_PROJECT_API_KEY ||\r\n process.env.BUGSTACK_API_KEY;\r\n const endpoint = resolveEndpoint(options.endpoint);\r\n const release = resolveRelease(options.release);\r\n const serverDir = options.serverDir || DEFAULT_SERVER_DIR;\r\n const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);\r\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\r\n const log = options.log || ((m: string) => console.log(m));\r\n const warn = options.warn || ((m: string) => console.warn(m));\r\n\r\n if (!apiKey) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly.\",\r\n );\r\n }\r\n if (!endpoint) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly.\",\r\n );\r\n }\r\n\r\n const start = Date.now();\r\n const mapFiles = await walk(serverDir);\r\n\r\n if (mapFiles.length === 0) {\r\n log(\r\n `[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`,\r\n );\r\n return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };\r\n }\r\n\r\n log(\r\n `[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || \"none\"})...`,\r\n );\r\n\r\n const results = await pool(mapFiles, concurrency, async (mapPath) => {\r\n const bundleFile = bundleFileFor(mapPath, serverDir);\r\n const stats = await stat(mapPath);\r\n if (stats.size > maxBytes) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: true,\r\n error: `Skipped — ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`,\r\n };\r\n }\r\n const mapJson = await readFile(mapPath, \"utf8\");\r\n try {\r\n const res = await fetch(endpoint, {\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n \"X-BugStack-API-Key\": apiKey,\r\n },\r\n body: JSON.stringify({ bundleFile, mapJson, release }),\r\n });\r\n if (!res.ok) {\r\n const text = await res.text().catch(() => \"\");\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: `HTTP ${res.status} ${text.slice(0, 200)}`,\r\n };\r\n }\r\n return { ok: true as const, bundleFile, bytes: stats.size, skipped: false };\r\n } catch (err) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: err instanceof Error ? err.message : String(err),\r\n };\r\n }\r\n });\r\n\r\n const uploaded = results.filter((r) => r.ok).length;\r\n const skipped = results.filter((r) => !r.ok && r.skipped).length;\r\n const failed = results.length - uploaded - skipped;\r\n const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);\r\n const failures = results\r\n .filter((r): r is Extract<typeof r, { ok: false }> => !r.ok && !r.skipped)\r\n .map((r) => ({ bundleFile: r.bundleFile, error: r.error }));\r\n const elapsedMs = Date.now() - start;\r\n\r\n log(\r\n `[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(\r\n 1,\r\n )}MB) in ${(elapsedMs / 1000).toFixed(1)}s.`,\r\n );\r\n if (skipped > 0) {\r\n warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);\r\n }\r\n if (failures.length > 0) {\r\n warn(`[bugstack] ${failures.length} upload(s) failed:`);\r\n for (const f of failures.slice(0, 10)) {\r\n warn(` - ${f.bundleFile}: ${f.error}`);\r\n }\r\n if (failures.length > 10) {\r\n warn(` …and ${failures.length - 10} more`);\r\n }\r\n }\r\n\r\n return { uploaded, skipped, failed, totalBytes, elapsedMs, failures };\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/build/upload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,CAAK,CAAA,YAAA,EAAU,QAAA,CAAS,MAAA,GAAS,EAAE,CAAA,KAAA,CAAO,CAAA;AAAA,IAC5C;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,MAAA,EAAQ,UAAA,EAAY,WAAW,QAAA,EAAS;AACtE","file":"upload.mjs","sourcesContent":["/**\n * Build-time source map uploader.\n *\n * Walks a directory of compiled output looking for `.map` files and POSTs\n * each one to the bugstack source-map ingest endpoint. The companion\n * `bugstack-sdk/next-config` wrapper enables emission of these maps for\n * Next.js server bundles; once uploaded, the orchestrator can resolve\n * production stack frames like \".next/server/chunks/8393.js:1:8734\" back\n * to source-file positions (\"app/api/orders/route.ts:42:5\") and actually\n * generate fixes for bundled errors.\n *\n * This module is import-safe in any Node 18+ environment. It uses no\n * runtime dependencies — `node:fs/promises` + global `fetch`.\n */\n\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join, relative, sep } from \"node:path\";\nimport { execSync } from \"node:child_process\";\n\nexport interface UploadSourceMapsOptions {\n /**\n * Project SDK key. Required. Reads BUGSTACK_PROJECT_API_KEY or\n * BUGSTACK_API_KEY when not supplied explicitly.\n */\n apiKey?: string;\n\n /**\n * Base URL of the bugstack ingest service. Reads BUGSTACK_ENDPOINT or\n * derives from ERROR_SERVICE_URL when not supplied. The uploader appends\n * `/api/sourcemaps/upload` to whatever base it gets.\n */\n endpoint?: string;\n\n /**\n * Release identifier (typically a commit SHA). Lets multiple deploys\n * coexist in the source-map table so old errors still resolve against\n * old maps. Auto-detected in this order:\n * 1. BUGSTACK_RELEASE\n * 2. RENDER_GIT_COMMIT\n * 3. VERCEL_GIT_COMMIT_SHA\n * 4. GITHUB_SHA\n * 5. `git rev-parse HEAD` (when a git checkout is present)\n */\n release?: string | null;\n\n /**\n * Directory to walk for `.map` files. Defaults to `.next/server`.\n * Override for non-Next projects (e.g. `dist` for tsc, `build` for CRA).\n */\n serverDir?: string;\n\n /**\n * Max concurrent uploads. Higher means faster builds, more pressure on\n * the ingest endpoint. Default 6 — tuned for Render's typical bandwidth.\n */\n concurrency?: number;\n\n /**\n * Per-file size cap in bytes. Maps larger than this are skipped with a\n * warning rather than failing. Default 8 MiB — covers typical\n * `.next/server/chunks/*.js.map` outputs comfortably.\n */\n maxBytes?: number;\n\n /**\n * Logger. Defaults to console. Pass a no-op logger to silence the\n * \"[bugstack] …\" lines in scripted environments.\n */\n log?: (message: string) => void;\n warn?: (message: string) => void;\n}\n\nexport interface UploadResult {\n uploaded: number;\n skipped: number;\n failed: number;\n totalBytes: number;\n elapsedMs: number;\n failures: Array<{ bundleFile: string; error: string }>;\n}\n\nconst DEFAULT_SERVER_DIR = \".next/server\";\nconst DEFAULT_CONCURRENCY = 6;\nconst DEFAULT_MAX_BYTES = 8 * 1024 * 1024;\nconst ENDPOINT_PATH = \"/api/sourcemaps/upload\";\n\nfunction resolveRelease(explicit?: string | null): string | null {\n if (explicit !== undefined) return explicit;\n const fromEnv =\n process.env.BUGSTACK_RELEASE ||\n process.env.RENDER_GIT_COMMIT ||\n process.env.VERCEL_GIT_COMMIT_SHA ||\n process.env.GITHUB_SHA;\n if (fromEnv) return fromEnv;\n try {\n return execSync(\"git rev-parse HEAD\", { stdio: [\"ignore\", \"pipe\", \"ignore\"] })\n .toString()\n .trim();\n } catch {\n return null;\n }\n}\n\nfunction resolveEndpoint(explicit?: string): string | null {\n const base =\n explicit ||\n process.env.BUGSTACK_ENDPOINT ||\n (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);\n if (!base) return null;\n // Strip trailing slashes + any trailing /api/capture or /capture so the\n // same env var that points the SDK at ingestion also works for sourcemaps.\n const normalised = base\n .replace(/\\/+$/, \"\")\n .replace(/\\/api\\/capture$/, \"\")\n .replace(/\\/capture$/, \"\");\n return normalised + ENDPOINT_PATH;\n}\n\nasync function walk(dir: string): Promise<string[]> {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n const out: string[] = [];\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n out.push(...(await walk(path)));\n } else if (entry.name.endsWith(\".map\")) {\n out.push(path);\n }\n }\n return out;\n}\n\nasync function pool<T, R>(\n items: T[],\n workers: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let i = 0;\n const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {\n while (i < items.length) {\n const idx = i++;\n results[idx] = await fn(items[idx]);\n }\n });\n await Promise.all(runners);\n return results;\n}\n\nfunction bundleFileFor(mapPath: string, serverDir: string): string {\n // Strip the serverDir prefix and the .map suffix; normalise Windows\n // backslashes so the bundleFile key stored on the server is portable\n // regardless of where the build ran.\n return relative(serverDir, mapPath)\n .replace(/\\.map$/, \"\")\n .split(sep)\n .join(\"/\");\n}\n\n/**\n * Upload every `.map` file under `serverDir` to the bugstack source-map\n * endpoint. Tolerant: never throws on individual file failures, returns\n * a summary the caller can decide what to do with.\n *\n * Throws only on hard configuration errors (no API key, no resolvable\n * endpoint, serverDir totally missing).\n */\nexport async function uploadSourceMaps(\n options: UploadSourceMapsOptions = {},\n): Promise<UploadResult> {\n const apiKey =\n options.apiKey ||\n process.env.BUGSTACK_PROJECT_API_KEY ||\n process.env.BUGSTACK_API_KEY;\n const endpoint = resolveEndpoint(options.endpoint);\n const release = resolveRelease(options.release);\n const serverDir = options.serverDir || DEFAULT_SERVER_DIR;\n const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n const log = options.log || ((m: string) => console.log(m));\n const warn = options.warn || ((m: string) => console.warn(m));\n\n if (!apiKey) {\n throw new Error(\n \"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly.\",\n );\n }\n if (!endpoint) {\n throw new Error(\n \"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly.\",\n );\n }\n\n const start = Date.now();\n const mapFiles = await walk(serverDir);\n\n if (mapFiles.length === 0) {\n log(\n `[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`,\n );\n return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };\n }\n\n log(\n `[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || \"none\"})...`,\n );\n\n const results = await pool(mapFiles, concurrency, async (mapPath) => {\n const bundleFile = bundleFileFor(mapPath, serverDir);\n const stats = await stat(mapPath);\n if (stats.size > maxBytes) {\n return {\n ok: false as const,\n bundleFile,\n bytes: 0,\n skipped: true,\n error: `Skipped — ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`,\n };\n }\n const mapJson = await readFile(mapPath, \"utf8\");\n try {\n const res = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-BugStack-API-Key\": apiKey,\n },\n body: JSON.stringify({ bundleFile, mapJson, release }),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n return {\n ok: false as const,\n bundleFile,\n bytes: 0,\n skipped: false,\n error: `HTTP ${res.status} ${text.slice(0, 200)}`,\n };\n }\n return { ok: true as const, bundleFile, bytes: stats.size, skipped: false };\n } catch (err) {\n return {\n ok: false as const,\n bundleFile,\n bytes: 0,\n skipped: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n });\n\n const uploaded = results.filter((r) => r.ok).length;\n const skipped = results.filter((r) => !r.ok && r.skipped).length;\n const failed = results.length - uploaded - skipped;\n const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);\n const failures = results\n .filter((r): r is Extract<typeof r, { ok: false }> => !r.ok && !r.skipped)\n .map((r) => ({ bundleFile: r.bundleFile, error: r.error }));\n const elapsedMs = Date.now() - start;\n\n log(\n `[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(\n 1,\n )}MB) in ${(elapsedMs / 1000).toFixed(1)}s.`,\n );\n if (skipped > 0) {\n warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);\n }\n if (failures.length > 0) {\n warn(`[bugstack] ${failures.length} upload(s) failed:`);\n for (const f of failures.slice(0, 10)) {\n warn(` - ${f.bundleFile}: ${f.error}`);\n }\n if (failures.length > 10) {\n warn(` …and ${failures.length - 10} more`);\n }\n }\n\n return { uploaded, skipped, failed, totalBytes, elapsedMs, failures };\n}\n"]}
|
|
@@ -1,5 +1,138 @@
|
|
|
1
1
|
import { NextRequest } from 'next/server';
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Caught-and-logged errors reach Bugstack.
|
|
5
|
+
*
|
|
6
|
+
* A `catch` that writes `console.error("[billing] grant failed", err)` and
|
|
7
|
+
* carries on is the commonest way an application handles a failure, and a log
|
|
8
|
+
* line is something nobody reads. Uncaught-exception handlers never see these
|
|
9
|
+
* errors because nothing re-throws them. On Bugstack's own repository, 12 of 16
|
|
10
|
+
* loud bugs it missed in one month were errors caught, logged and carried on
|
|
11
|
+
* from.
|
|
12
|
+
*
|
|
13
|
+
* This module forwards them through the same client every other capture path
|
|
14
|
+
* uses (`ErrorCaptureClient.reportError`), so they get the same `beforeSend`,
|
|
15
|
+
* the same fingerprint dedup and the same transport. Three sources feed it:
|
|
16
|
+
*
|
|
17
|
+
* - `console.error`, wrapped once per process when a client is initialised
|
|
18
|
+
* (on by default; `captureConsoleErrors: false` turns it off);
|
|
19
|
+
* - pino, through `bugstackPinoHooks()` (error and fatal);
|
|
20
|
+
* - winston, through `bugstackWinstonFormat()` (error and above).
|
|
21
|
+
*
|
|
22
|
+
* Rules, each tested in test/logged-errors.test.ts:
|
|
23
|
+
*
|
|
24
|
+
* - THE CONSOLE LINE IS WRITTEN EXACTLY AS BEFORE, first, with the same
|
|
25
|
+
* arguments and `this`. Forwarding happens after, and never throws.
|
|
26
|
+
* - WHAT IS FORWARDED: a call carrying an Error (as an argument, or as the
|
|
27
|
+
* `err` / `error` field of an object argument, the pino shape), or a string
|
|
28
|
+
* holding a stack trace (`console.error("failed", err.stack)`). A plain
|
|
29
|
+
* message with neither is noise by default and stays a console line;
|
|
30
|
+
* `{ messages: true }` forwards it too, as its text.
|
|
31
|
+
* - NOT FORWARDED, counted per rule in `loggedErrorStats()`: the SDK's own
|
|
32
|
+
* `[BugStack…]` lines, Node's process warnings (`(node:1) [DEP0169]
|
|
33
|
+
* DeprecationWarning: …`, which Node writes through console.error), lines
|
|
34
|
+
* matching `ignore`, an error an adapter already reported
|
|
35
|
+
* (`markErrorReported`), the same site and message again within
|
|
36
|
+
* `repeatWindowMs`, and anything past `maxPerMinute`.
|
|
37
|
+
* - ANCHORED AT THE LOGGING SITE. The fingerprint is error type + route +
|
|
38
|
+
* first stack frame. A driver error has the same first frame wherever it
|
|
39
|
+
* was caught, so the report is a new `LoggedError` whose stack starts at
|
|
40
|
+
* the line that logged it. The original rides along as `cause` and, as
|
|
41
|
+
* `causeName` / `causeStack`, in metadata.
|
|
42
|
+
* - NEVER TWICE. Forwarding is deferred one macrotask, so a catch that logs
|
|
43
|
+
* and then calls `captureError` in the same tick sends once.
|
|
44
|
+
* - NEVER LOOPS. A console.error raised while reporting (by `beforeSend`, or
|
|
45
|
+
* by the SDK's own debug logging) is written and not forwarded.
|
|
46
|
+
* - REDACTED. The text of a logged line goes through the client's
|
|
47
|
+
* `redactFields` (`password=…`, `token: …`) and `Bearer …` is masked.
|
|
48
|
+
* Only message text and stacks are sent, never the other log arguments.
|
|
49
|
+
*
|
|
50
|
+
* State lives on `globalThis` under a registered symbol: each package entry
|
|
51
|
+
* point (`bugstack-sdk`, `bugstack-sdk/generic`, …) is bundled on its own, and
|
|
52
|
+
* there must still be one console wrap and one "already reported" set per
|
|
53
|
+
* process.
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
/** Options for `captureConsoleErrors`. Every field is optional. */
|
|
57
|
+
interface LoggedErrorOptions {
|
|
58
|
+
/**
|
|
59
|
+
* Also forward a console.error (or logger error) that carries no Error and
|
|
60
|
+
* no stack trace, as its message text. Off by default: many libraries write
|
|
61
|
+
* plain lines through console.error that are not failures of your app.
|
|
62
|
+
* @default false
|
|
63
|
+
*/
|
|
64
|
+
messages?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* At most this many logged errors are forwarded per minute, per process.
|
|
67
|
+
* @default 20
|
|
68
|
+
*/
|
|
69
|
+
maxPerMinute?: number;
|
|
70
|
+
/**
|
|
71
|
+
* The same logging site with the same message is forwarded at most once per
|
|
72
|
+
* this window (milliseconds). A message-only line repeats per site alone,
|
|
73
|
+
* because its text usually carries ids.
|
|
74
|
+
* @default 300000 (5 minutes)
|
|
75
|
+
*/
|
|
76
|
+
repeatWindowMs?: number;
|
|
77
|
+
/**
|
|
78
|
+
* Lines whose text matches any of these stay console lines.
|
|
79
|
+
*/
|
|
80
|
+
ignore?: Array<string | RegExp>;
|
|
81
|
+
}
|
|
82
|
+
/** Where a logged error came from. */
|
|
83
|
+
type LoggedErrorSource = "console-error" | "pino" | "winston";
|
|
84
|
+
/** Why a logged error was not forwarded, counted per rule. */
|
|
85
|
+
type LoggedErrorDropRule = "no_error_argument" | "sdk_line" | "node_warning" | "ignored" | "already_reported" | "repeat" | "rate_limited" | "no_client";
|
|
86
|
+
interface ResolvedLoggedErrorOptions {
|
|
87
|
+
console: boolean;
|
|
88
|
+
messages: boolean;
|
|
89
|
+
maxPerMinute: number;
|
|
90
|
+
repeatWindowMs: number;
|
|
91
|
+
ignore: Array<string | RegExp>;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Say this error was already sent to Bugstack, so a console line or logger
|
|
95
|
+
* call for the same error object is not sent again. The SDK's adapters call
|
|
96
|
+
* it; call it yourself if you report an error through your own wrapper.
|
|
97
|
+
*/
|
|
98
|
+
declare function markErrorReported(error: unknown): void;
|
|
99
|
+
/** Forwarded and dropped counts since the process started, dropped counted per rule. */
|
|
100
|
+
declare function loggedErrorStats(): {
|
|
101
|
+
consoleInstalled: boolean;
|
|
102
|
+
forwarded: number;
|
|
103
|
+
messageOnly: number;
|
|
104
|
+
dropped: Record<LoggedErrorDropRule, number>;
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* pino `hooks` that forward error and fatal logs. Pass to pino:
|
|
108
|
+
*
|
|
109
|
+
* ```ts
|
|
110
|
+
* const logger = pino({ hooks: bugstackPinoHooks() });
|
|
111
|
+
* ```
|
|
112
|
+
*
|
|
113
|
+
* If you already use `hooks.logMethod`, call the returned `logMethod` from
|
|
114
|
+
* yours. The log line is written exactly as before.
|
|
115
|
+
*/
|
|
116
|
+
declare function bugstackPinoHooks(): {
|
|
117
|
+
logMethod: (this: unknown, inputArgs: unknown[], method: (...a: unknown[]) => unknown, level: number) => unknown;
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* A winston format that forwards error-level logs. Put it first in your
|
|
121
|
+
* format chain:
|
|
122
|
+
*
|
|
123
|
+
* ```ts
|
|
124
|
+
* const logger = winston.createLogger({
|
|
125
|
+
* format: winston.format.combine(bugstackWinstonFormat(), winston.format.json()),
|
|
126
|
+
* transports: [new winston.transports.Console()],
|
|
127
|
+
* });
|
|
128
|
+
* ```
|
|
129
|
+
*
|
|
130
|
+
* It returns the log entry unchanged.
|
|
131
|
+
*/
|
|
132
|
+
declare function bugstackWinstonFormat(): {
|
|
133
|
+
transform: (info: Record<string | symbol, unknown>) => Record<string | symbol, unknown>;
|
|
134
|
+
};
|
|
135
|
+
|
|
3
136
|
/**
|
|
4
137
|
* Configuration options for the BugStack error capture SDK
|
|
5
138
|
*/
|
|
@@ -10,7 +143,7 @@ interface ErrorCaptureConfig {
|
|
|
10
143
|
apiKey: string;
|
|
11
144
|
/**
|
|
12
145
|
* URL of the BugStack error service endpoint
|
|
13
|
-
* @default process.env.BUGSTACK_ENDPOINT || "
|
|
146
|
+
* @default process.env.BUGSTACK_ENDPOINT || "https://dashboard.bugstack.ai/api/ingest/sdk"
|
|
14
147
|
*/
|
|
15
148
|
endpoint?: string;
|
|
16
149
|
/**
|
|
@@ -114,6 +247,18 @@ interface ErrorCaptureConfig {
|
|
|
114
247
|
* lives behind a different host/path for telemetry vs. main capture.
|
|
115
248
|
*/
|
|
116
249
|
chunkErrorsEndpoint?: string;
|
|
250
|
+
/**
|
|
251
|
+
* Forward caught-and-logged errors: a `console.error` call that carries an
|
|
252
|
+
* Error (or a stack trace) is reported, anchored at the line that logged it.
|
|
253
|
+
* The console line is written exactly as before. On by default; `false`
|
|
254
|
+
* turns it off. Pass options to tune it, e.g. `{ messages: true }` to also
|
|
255
|
+
* forward console.error lines that carry only a message.
|
|
256
|
+
*
|
|
257
|
+
* pino and winston are covered through `bugstackPinoHooks()` and
|
|
258
|
+
* `bugstackWinstonFormat()`, which follow the same rules.
|
|
259
|
+
* @default true
|
|
260
|
+
*/
|
|
261
|
+
captureConsoleErrors?: boolean | LoggedErrorOptions;
|
|
117
262
|
}
|
|
118
263
|
/**
|
|
119
264
|
* Resolved configuration with all defaults applied
|
|
@@ -138,6 +283,7 @@ interface ResolvedConfig {
|
|
|
138
283
|
beforeSend?: (error: CapturedError) => CapturedError | null;
|
|
139
284
|
dropChunkErrors: boolean;
|
|
140
285
|
chunkErrorsEndpoint: string;
|
|
286
|
+
captureConsoleErrors: ResolvedLoggedErrorOptions;
|
|
141
287
|
}
|
|
142
288
|
/**
|
|
143
289
|
* Captured error data sent to the error service
|
|
@@ -576,6 +722,7 @@ declare class ErrorCaptureClient {
|
|
|
576
722
|
private static instance;
|
|
577
723
|
private deduplicator;
|
|
578
724
|
private retryQueue;
|
|
725
|
+
private loggedErrorSink;
|
|
579
726
|
constructor(config: ErrorCaptureConfig);
|
|
580
727
|
/**
|
|
581
728
|
* Initialize the singleton client instance
|
|
@@ -660,4 +807,4 @@ declare function isChunkLoadError(error: {
|
|
|
660
807
|
message?: string;
|
|
661
808
|
}): boolean;
|
|
662
809
|
|
|
663
|
-
export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, type RouteOptions as
|
|
810
|
+
export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type LoggedErrorOptions as L, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, bugstackPinoHooks as b, bugstackWinstonFormat as c, type RouteOptions as d, type BugStackConfig as e, ErrorDeduplicator as f, type ErrorReportPayload as g, type LoggedErrorDropRule as h, type LoggedErrorSource as i, type ResolvedConfig as j, RetryQueue as k, loggedErrorStats as l, markErrorReported as m, type SourceContext as n, isChunkLoadError as o };
|