@getmonitor/cli 0.3.3 → 0.3.5
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/README.md +1 -1
- package/dist/bin.js +66 -22
- package/dist/bin.js.map +1 -1
- package/dist/index.cjs +59 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +59 -22
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +6 -0
- package/dist/uploadSourceMap.d.ts +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ as part of a customer's build.
|
|
|
9
9
|
For every `*.js` file with a resolvable source map under a directory, `processSourceMaps`:
|
|
10
10
|
|
|
11
11
|
1. Generates a debug ID and injects it into both the JS file and its source map.
|
|
12
|
-
2. Uploads the tagged source map to `https://
|
|
12
|
+
2. Uploads the tagged source map to `https://track.getmonitor.io/api/v1/sourcemaps` — the
|
|
13
13
|
upload host is fixed and not customer-configurable.
|
|
14
14
|
3. On a successful upload: deletes the `.map` file and strips the `//# sourceMappingURL=`
|
|
15
15
|
comment from the JS file, so nothing readable ships publicly.
|
package/dist/bin.js
CHANGED
|
@@ -172,7 +172,7 @@ function tryPackageVersion(directory) {
|
|
|
172
172
|
|
|
173
173
|
// packages/cli/src/uploadSourceMap.ts
|
|
174
174
|
/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */
|
|
175
|
-
const DEFAULT_API_HOST = 'https://
|
|
175
|
+
const DEFAULT_API_HOST = 'https://track.getmonitor.io';
|
|
176
176
|
/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.
|
|
177
177
|
* Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides
|
|
178
178
|
* what "failed" means for its own result reporting and disk-write ordering. */
|
|
@@ -197,7 +197,11 @@ async function uploadSourceMap(params) {
|
|
|
197
197
|
body: form,
|
|
198
198
|
});
|
|
199
199
|
if (!response.ok) {
|
|
200
|
-
|
|
200
|
+
// Deliberately excludes `params.filename` — a real deployment can have hundreds/thousands
|
|
201
|
+
// of artifacts fail identically (e.g. one bad auth token), and processSourceMaps
|
|
202
|
+
// deduplicates these messages to log the reason once instead of once per file. Baking the
|
|
203
|
+
// filename in here would make every message unique and defeat that dedup.
|
|
204
|
+
throw new Error(`${response.status} ${response.statusText}`);
|
|
201
205
|
}
|
|
202
206
|
}
|
|
203
207
|
|
|
@@ -221,24 +225,42 @@ async function processSourceMaps(options) {
|
|
|
221
225
|
}
|
|
222
226
|
const release = resolveRelease(options.directory, options.release);
|
|
223
227
|
const artifacts = discoverArtifacts(options.directory);
|
|
224
|
-
// Indexed by each artifact's position in `artifacts` rather than appended in completion
|
|
225
|
-
// order, so the final result below is deterministic no matter which worker finishes first.
|
|
226
228
|
const outcomes = new Array(artifacts.length);
|
|
227
229
|
const processOne = async (index) => {
|
|
228
230
|
const artifact = artifacts[index];
|
|
229
231
|
const debugId = randomUUID();
|
|
230
232
|
let injected;
|
|
233
|
+
// Local step: reading the artifact and injecting its debug ID. A failure here (unreadable
|
|
234
|
+
// file, malformed map JSON) means the build's own output is broken — that's a real bug
|
|
235
|
+
// worth failing CI over, so it's tracked in `failed` and logged per-file: with a genuine
|
|
236
|
+
// local bug there are normally only one or a handful of these, unlike a systemic upload
|
|
237
|
+
// outage below.
|
|
231
238
|
try {
|
|
232
239
|
const originalJs = readFileSync(artifact.jsPath, 'utf8');
|
|
233
240
|
const originalMap = readFileSync(artifact.mapPath, 'utf8');
|
|
234
241
|
// injectDebugId is a pure function that throws on malformed map JSON (by design — see
|
|
235
|
-
// its own doc comment).
|
|
236
|
-
//
|
|
237
|
-
//
|
|
238
|
-
//
|
|
239
|
-
//
|
|
240
|
-
//
|
|
242
|
+
// its own doc comment). One corrupt/unreadable artifact on disk must not abort
|
|
243
|
+
// processing of every other artifact in the directory, the same failure-isolation
|
|
244
|
+
// principle discoverArtifacts applies to unreadable files during its walk. Nothing has
|
|
245
|
+
// been uploaded or written yet at this point, so a thrown injectDebugId failure leaves
|
|
246
|
+
// the artifact's files completely untouched, and it's safe to report it as `failed` for
|
|
247
|
+
// a retry.
|
|
241
248
|
injected = injectDebugId(originalJs, originalMap, debugId);
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error);
|
|
252
|
+
outcomes[index] = { path: artifact.jsPath, kind: 'failed' };
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
// Remote step: uploading to the ingest API. Unlike the local step above, this artifact was
|
|
256
|
+
// perfectly fine — the *endpoint* rejected the request or was unreachable (bad/expired auth
|
|
257
|
+
// token, network outage, backend 5xx). That's an infra/connectivity problem outside this
|
|
258
|
+
// build's control, not a bug in it, so it's tracked separately in `skipped` (never `failed`)
|
|
259
|
+
// and deliberately NOT logged per-file here: an outage or bad token fails every one of
|
|
260
|
+
// potentially thousands of artifacts identically, and logging each one would drown out
|
|
261
|
+
// everything else in the build's output. The deduplicated reason is logged once, after all
|
|
262
|
+
// artifacts finish, by the summary block below.
|
|
263
|
+
try {
|
|
242
264
|
await uploadSourceMap({
|
|
243
265
|
apiHost: options.apiHost,
|
|
244
266
|
authToken,
|
|
@@ -252,27 +274,26 @@ async function processSourceMaps(options) {
|
|
|
252
274
|
});
|
|
253
275
|
}
|
|
254
276
|
catch (error) {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
outcomes[index] = { path: artifact.jsPath, ok: false };
|
|
277
|
+
outcomes[index] = {
|
|
278
|
+
path: artifact.jsPath,
|
|
279
|
+
kind: 'skipped',
|
|
280
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
281
|
+
};
|
|
261
282
|
return;
|
|
262
283
|
}
|
|
263
284
|
try {
|
|
264
285
|
writeFileSync(artifact.jsPath, injected.js);
|
|
265
286
|
rmSync(artifact.mapPath);
|
|
266
|
-
outcomes[index] = { path: artifact.jsPath,
|
|
287
|
+
outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' };
|
|
267
288
|
}
|
|
268
289
|
catch (cleanupError) {
|
|
269
|
-
// The upload above already succeeded, so this must never land in `failed`
|
|
270
|
-
// retrying
|
|
290
|
+
// The upload above already succeeded, so this must never land in `failed` or `skipped` —
|
|
291
|
+
// a caller retrying either would mint a fresh debugId and re-upload, orphaning this
|
|
271
292
|
// upload server-side under the old one with no way to reconcile the two. The local
|
|
272
293
|
// cleanup failure (disk full, permission error, file lock) is real and worth knowing
|
|
273
294
|
// about, so it's surfaced here rather than silently swallowed, but it doesn't change
|
|
274
295
|
// the artifact's outcome.
|
|
275
|
-
outcomes[index] = { path: artifact.jsPath,
|
|
296
|
+
outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' };
|
|
276
297
|
console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError);
|
|
277
298
|
}
|
|
278
299
|
};
|
|
@@ -287,9 +308,25 @@ async function processSourceMaps(options) {
|
|
|
287
308
|
};
|
|
288
309
|
const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length);
|
|
289
310
|
await Promise.all(Array.from({ length: workerCount }, runWorker));
|
|
290
|
-
const result = { uploaded: [], failed: [] };
|
|
311
|
+
const result = { uploaded: [], failed: [], skipped: [] };
|
|
312
|
+
// Counts occurrences of each distinct skip reason, preserving first-seen order, so the
|
|
313
|
+
// summary below reads one line per *kind* of problem rather than one line per file.
|
|
314
|
+
const skipReasonCounts = new Map();
|
|
291
315
|
for (const outcome of outcomes) {
|
|
292
|
-
(outcome.
|
|
316
|
+
if (outcome.kind === 'uploaded')
|
|
317
|
+
result.uploaded.push(outcome.path);
|
|
318
|
+
else if (outcome.kind === 'failed')
|
|
319
|
+
result.failed.push(outcome.path);
|
|
320
|
+
else {
|
|
321
|
+
result.skipped.push(outcome.path);
|
|
322
|
+
skipReasonCounts.set(outcome.reason, (skipReasonCounts.get(outcome.reason) ?? 0) + 1);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
if (result.skipped.length > 0) {
|
|
326
|
+
console.warn(`GetMonitor: could not upload ${result.skipped.length} source map(s); continuing without them.`);
|
|
327
|
+
for (const [reason, count] of skipReasonCounts) {
|
|
328
|
+
console.warn(` - ${reason} (${count}x)`);
|
|
329
|
+
}
|
|
293
330
|
}
|
|
294
331
|
return result;
|
|
295
332
|
}
|
|
@@ -323,6 +360,13 @@ async function main() {
|
|
|
323
360
|
authToken: args.authToken,
|
|
324
361
|
});
|
|
325
362
|
console.log(`Uploaded ${result.uploaded.length} source map(s).`);
|
|
363
|
+
if (result.skipped.length > 0) {
|
|
364
|
+
// Non-fatal by design: processSourceMaps already warned with the reason(s) above. This is
|
|
365
|
+
// a plain summary line, not an error — exitCode must stay 0 when the only problem was an
|
|
366
|
+
// unreachable/unauthenticated upload endpoint, not a bug in this build's output, so a
|
|
367
|
+
// `next build && getmonitor sourcemaps upload` pipeline still succeeds overall.
|
|
368
|
+
console.log(`Skipped ${result.skipped.length} source map(s) due to upload errors (see warnings above).`);
|
|
369
|
+
}
|
|
326
370
|
if (result.failed.length > 0) {
|
|
327
371
|
console.error(`Failed to upload ${result.failed.length} source map(s):`);
|
|
328
372
|
for (const file of result.failed)
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.js","sources":["../src/discoverArtifacts.ts","../src/injectDebugId.ts","../src/resolveRelease.ts","../src/uploadSourceMap.ts","../src/processSourceMaps.ts","../src/bin.ts"],"sourcesContent":["// packages/cli/src/discoverArtifacts.ts\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Artifact {\n jsPath: string\n mapPath: string\n}\n\nconst SOURCE_MAPPING_URL = /^\\s*\\/\\/#\\s*sourceMappingURL=(\\S+)\\s*$/gm\n\n// Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit\n// ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's \"type\") — all three\n// show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e\n// test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real\n// `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and\n// unstripped even though `.output/` itself was already fully written by the time discovery ran.\nconst JS_EXTENSIONS = ['.js', '.mjs', '.cjs']\n\n/** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its\n * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the\n * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,\n * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no\n * resolvable map either way is skipped. */\nexport function discoverArtifacts(directory: string): Artifact[] {\n const artifacts: Artifact[] = []\n walk(directory, artifacts)\n return artifacts\n}\n\nfunction walk(dir: string, artifacts: Artifact[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n walk(fullPath, artifacts)\n } else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {\n const mapPath = resolveMapPath(fullPath)\n if (mapPath) artifacts.push({ jsPath: fullPath, mapPath })\n }\n }\n}\n\nfunction resolveMapPath(jsPath: string): string | undefined {\n const commentMapPath = readSourceMappingUrlComment(jsPath)\n if (commentMapPath && existsSync(commentMapPath)) return commentMapPath\n\n const fallbackMapPath = `${jsPath}.map`\n if (existsSync(fallbackMapPath)) return fallbackMapPath\n\n return undefined\n}\n\nfunction readSourceMappingUrlComment(jsPath: string): string | undefined {\n let content: string\n try {\n content = readFileSync(jsPath, 'utf8')\n } catch {\n // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it\n // like \"no comment found\" rather than aborting the whole discoverArtifacts() walk.\n return undefined\n }\n\n const matches = [...content.matchAll(SOURCE_MAPPING_URL)]\n if (matches.length === 0) return undefined\n\n // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat\n // concatenated/reprocessed output — later comments supersede earlier ones.\n const reference = matches.at(-1)![1]\n if (reference.startsWith('data:')) return undefined // embedded map, nothing to discover on disk\n\n return join(dirname(jsPath), reference)\n}\n","// packages/cli/src/injectDebugId.ts\n\nexport interface InjectedArtifact {\n js: string\n map: string\n}\n\n/** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in\n * memory — callers decide whether/when to persist the result to disk (processSourceMaps\n * only writes it after a successful upload, so a failed upload never leaves partially\n * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)\n * removed, since the source map it names is only ever kept in GetMonitor's backend after\n * a successful upload — never served publicly alongside it.\n *\n * `originalMapJson` must be valid JSON — this is a pure function with no fallback to\n * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's\n * caller expects a definite result), so a malformed map is left to throw via JSON.parse\n * rather than being swallowed here. */\nexport function injectDebugId(originalJs: string, originalMapJson: string, debugId: string): InjectedArtifact {\n const withoutMapComment = originalJs\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))\n .join('\\n')\n\n const map = JSON.parse(originalMapJson)\n map.debugId = debugId\n\n return {\n js: `${withoutMapComment}\\n${buildInjectedSnippet(debugId)}`,\n map: JSON.stringify(map),\n }\n}\n\n/** At load time, captures this statement's own `Error().stack`, extracts this file's\n * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for\n * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's\n * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,\n * it scans every stack line and takes the first one that matches any of those shapes, rather\n * than assuming a fixed line index — V8 prefixes an `\"ErrorType: message\"` header line that\n * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong\n * file's identity) on non-V8 engines; the header line simply fails to match any frame regex\n * and is skipped automatically. A later real error whose frame.filename is parsed from the\n * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any\n * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak\n * into the file's module scope.\n *\n * `debugId` is interpolated unescaped into the generated snippet's string literal. That's\n * safe today because every caller in this system sources `debugId` from\n * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but\n * this function itself doesn't enforce that shape, so a caller passing an arbitrary string\n * containing `'` or `\\` would produce invalid/injected JS here. Flagged, not fixed, since\n * validating/escaping isn't part of this function's specified contract. */\nfunction buildInjectedSnippet(debugId: string): string {\n return (\n \";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\\\n');var m=null;\" +\n 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +\n \"m=l.match(/\\\\((.*):(\\\\d+):(\\\\d+)\\\\)\\\\s*$/)||l.match(/at (.*):(\\\\d+):(\\\\d+)\\\\s*$/)||l.match(/@(.*):(\\\\d+):(\\\\d+)\\\\s*$/)}\" +\n \"var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);\" +\n `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +\n '}}catch(e){}})();'\n )\n}\n","// packages/cli/src/resolveRelease.ts\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit\n * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside\n * a git working tree) -> `version` field of the nearest package.json walking up from\n * `directory`. Matches the SDKs' own optional `release` field so events and source maps\n * for the same deploy carry the same value. */\nexport function resolveRelease(directory: string, explicit?: string): string {\n if (explicit) return explicit\n if (process.env.GETMONITOR_RELEASE) return process.env.GETMONITOR_RELEASE\n\n const gitSha = tryGitSha(directory)\n if (gitSha) return gitSha\n\n const packageVersion = tryPackageVersion(directory)\n if (packageVersion) return packageVersion\n\n throw new Error(\n 'Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a \"version\" field.',\n )\n}\n\nfunction tryGitSha(directory: string): string | undefined {\n try {\n return execFileSync('git', ['rev-parse', 'HEAD'], {\n cwd: directory,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim()\n } catch {\n return undefined\n }\n}\n\nfunction tryPackageVersion(directory: string): string | undefined {\n let dir = directory\n for (let i = 0; i < 20; i++) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n return typeof pkg.version === 'string' ? pkg.version : undefined\n } catch {\n return undefined\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n return undefined\n}\n","// packages/cli/src/uploadSourceMap.ts\n\n/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */\nexport const DEFAULT_API_HOST = 'https://ingest.getmonitor.io'\n\nexport interface UploadSourceMapParams {\n /**\n * @internal Test-only override for redirecting delivery to a local mock server (see\n * cli/e2e/processSourceMaps.spec.ts and the nextjs-config/nuxt e2e suites). Never exposed\n * through the public CLI/programmatic surface — real usage always ships to\n * {@link DEFAULT_API_HOST}.\n */\n apiHost?: string\n authToken: string\n release: string\n debugId: string\n filename: string\n mapContent: string\n fetchImpl?: typeof fetch\n}\n\n/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.\n * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides\n * what \"failed\" means for its own result reporting and disk-write ordering. */\nexport async function uploadSourceMap(params: UploadSourceMapParams): Promise<void> {\n // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native\n // fetch() throws \"Illegal invocation\" if called with a `this` other than\n // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below\n // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this\n // bind is defensive/consistent rather than load-bearing for this particular call site — but\n // keeping the same default expression as HttpTransport avoids a divergent default if this\n // code is ever refactored into a method.\n const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis)\n const apiHost = params.apiHost ?? DEFAULT_API_HOST\n\n const form = new FormData()\n form.set('release', params.release)\n form.set('debugId', params.debugId)\n form.set('filename', params.filename)\n form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`)\n\n const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${params.authToken}` },\n body: form,\n })\n\n if (!response.ok) {\n throw new Error(`Source map upload failed for ${params.filename}: ${response.status} ${response.statusText}`)\n }\n}\n","// packages/cli/src/processSourceMaps.ts\nimport { randomUUID } from 'node:crypto'\nimport { readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { relative } from 'node:path'\nimport { discoverArtifacts } from './discoverArtifacts'\nimport { injectDebugId, InjectedArtifact } from './injectDebugId'\nimport { resolveRelease } from './resolveRelease'\nimport { uploadSourceMap } from './uploadSourceMap'\nimport { ProcessSourceMapsOptions, ProcessSourceMapsResult } from './types'\n\n/**\n * @internal Test-only host override, intersected into `processSourceMaps`'s options but\n * deliberately not part of the exported `ProcessSourceMapsOptions` type — see\n * `uploadSourceMap`'s `UploadSourceMapParams.apiHost`. Used by this package's own e2e suite\n * and by nextjs-config/nuxt's e2e suites (via their own internal overrides) to redirect\n * delivery to a local mock server; real callers must never set it.\n */\ninterface InternalTestOverrides {\n apiHost?: string\n}\n\n/** Number of artifacts uploaded at once. Each upload is an independent network round trip to\n * ingester-api, so processing them one at a time made wall-clock time scale linearly with\n * artifact count for no reason — a real Next.js build can emit well over a thousand of them,\n * turning a few hundred ms of per-file latency into many minutes of serial waiting. */\nconst UPLOAD_CONCURRENCY = 20\n\n/** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a\n * debug ID, uploads the tagged source map, and — only on a successful upload — writes the\n * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload\n * fails is left completely untouched on disk, so it can be retried by re-running this\n * function against the same directory. Artifacts are uploaded concurrently (bounded by\n * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match\n * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */\nexport async function processSourceMaps(\n options: ProcessSourceMapsOptions & InternalTestOverrides\n): Promise<ProcessSourceMapsResult> {\n const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN\n if (!authToken) {\n throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.')\n }\n\n const release = resolveRelease(options.directory, options.release)\n const artifacts = discoverArtifacts(options.directory)\n // Indexed by each artifact's position in `artifacts` rather than appended in completion\n // order, so the final result below is deterministic no matter which worker finishes first.\n const outcomes: Array<{ path: string; ok: boolean }> = new Array(artifacts.length)\n\n const processOne = async (index: number): Promise<void> => {\n const artifact = artifacts[index]\n const debugId = randomUUID()\n let injected: InjectedArtifact\n\n try {\n const originalJs = readFileSync(artifact.jsPath, 'utf8')\n const originalMap = readFileSync(artifact.mapPath, 'utf8')\n // injectDebugId is a pure function that throws on malformed map JSON (by design — see\n // its own doc comment). That's deliberately caught here, alongside upload failures: one\n // corrupt/unreadable artifact on disk must not abort processing of every other artifact\n // in the directory, the same failure-isolation principle discoverArtifacts applies to\n // unreadable files during its walk. Nothing has been uploaded or written yet at this\n // point, so a thrown injectDebugId or upload failure leaves the artifact's files\n // completely untouched, and it's safe to report it as `failed` for a retry.\n injected = injectDebugId(originalJs, originalMap, debugId)\n\n await uploadSourceMap({\n apiHost: options.apiHost,\n authToken,\n release,\n debugId,\n // Relative to options.directory, not the absolute on-disk path — the backend has no\n // use for (and shouldn't see) the build machine's local filesystem layout.\n filename: relative(options.directory, artifact.jsPath),\n mapContent: injected.map,\n fetchImpl: options.fetchImpl,\n })\n } catch (error) {\n // Surfaced here rather than swallowed: this is the only place the actual failure reason\n // (injectDebugId's malformed-JSON error, or uploadSourceMap's `status statusText` message)\n // is available. Without logging it, callers only ever see a bare list of failed paths with\n // no way to tell an auth failure from a malformed map from a network error.\n console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error)\n outcomes[index] = { path: artifact.jsPath, ok: false }\n return\n }\n\n try {\n writeFileSync(artifact.jsPath, injected.js)\n rmSync(artifact.mapPath)\n outcomes[index] = { path: artifact.jsPath, ok: true }\n } catch (cleanupError) {\n // The upload above already succeeded, so this must never land in `failed` — a caller\n // retrying failed artifacts would mint a fresh debugId and re-upload, orphaning this\n // upload server-side under the old one with no way to reconcile the two. The local\n // cleanup failure (disk full, permission error, file lock) is real and worth knowing\n // about, so it's surfaced here rather than silently swallowed, but it doesn't change\n // the artifact's outcome.\n outcomes[index] = { path: artifact.jsPath, ok: true }\n console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError)\n }\n }\n\n // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared\n // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.\n let nextIndex = 0\n const runWorker = async (): Promise<void> => {\n while (nextIndex < artifacts.length) {\n const index = nextIndex++\n await processOne(index)\n }\n }\n const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length)\n await Promise.all(Array.from({ length: workerCount }, runWorker))\n\n const result: ProcessSourceMapsResult = { uploaded: [], failed: [] }\n for (const outcome of outcomes) {\n ;(outcome.ok ? result.uploaded : result.failed).push(outcome.path)\n }\n return result\n}\n","// packages/cli/src/bin.ts\nimport { processSourceMaps } from './processSourceMaps'\n\ninterface ParsedArgs {\n directory: string\n release?: string\n authToken?: string\n}\n\n/** Exported (not just used internally) so it's unit-testable without spawning a process. */\nexport function parseArgs(argv: string[]): ParsedArgs {\n const [command, subcommand, directory, ...rest] = argv\n if (command !== 'sourcemaps' || subcommand !== 'upload' || !directory) {\n throw new Error(\n 'Usage: getmonitor sourcemaps upload <directory> [--release <release>] [--auth-token <token>]',\n )\n }\n\n let release: string | undefined\n let authToken: string | undefined\n\n for (let i = 0; i < rest.length; i += 2) {\n const flag = rest[i]\n const value = rest[i + 1]\n if (flag === '--release') release = value\n else if (flag === '--auth-token') authToken = value\n else throw new Error(`Unknown flag: ${flag}`)\n }\n\n return { directory, release, authToken }\n}\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2))\n\n const result = await processSourceMaps({\n directory: args.directory,\n release: args.release,\n authToken: args.authToken,\n })\n\n console.log(`Uploaded ${result.uploaded.length} source map(s).`)\n if (result.failed.length > 0) {\n console.error(`Failed to upload ${result.failed.length} source map(s):`)\n for (const file of result.failed) console.error(` ${file}`)\n process.exitCode = 1\n }\n}\n\n// Skipped under Vitest (which imports this module to test parseArgs) — only run when\n// invoked directly as the built dist/bin.js executable. Confirmed empirically that Vitest\n// sets process.env.VITEST = 'true' in the process that loads this module, so this check\n// reliably prevents main() (which does real I/O and can set process.exitCode) from running\n// during `pnpm test`.\nif (process.env.VITEST === undefined) {\n main().catch((error) => {\n console.error(error instanceof Error ? error.message : error)\n process.exitCode = 1\n })\n}\n"],"names":[],"mappings":";;;;;;AAAA;AASA,MAAM,kBAAkB,GAAG,0CAA0C;AAErE;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;AAE7C;;;;AAI2C;AACrC,SAAU,iBAAiB,CAAC,SAAiB,EAAA;IACjD,MAAM,SAAS,GAAe,EAAE;AAChC,IAAA,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC;AAC1B,IAAA,OAAO,SAAS;AAClB;AAEA,SAAS,IAAI,CAAC,GAAW,EAAE,SAAqB,EAAA;AAC9C,IAAA,KAAK,MAAM,KAAK,IAAI,WAAW,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,EAAE;QAC7D,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC;AACtC,QAAA,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE;AACvB,YAAA,IAAI,CAAC,QAAQ,EAAE,SAAS,CAAC;QAC3B;aAAO,IAAI,KAAK,CAAC,MAAM,EAAE,IAAI,aAAa,CAAC,IAAI,CAAC,CAAC,GAAG,KAAK,KA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AChE,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;QAC5B,OAAO,CAAC,KAAK,CAAC,CAAA,iBAAA,EAAoB,MAAM,CAAC,MAAM,CAAC,MAAM,CAAA,eAAA,CAAiB,CAAC;AACxE,QAAA,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,MAAM;AAAE,YAAA,OAAO,CAAC,KAAK,CAAC,KAAK,IAAI,CAAA,CAAE,CAAC;AAC5D,QAAA,OAAO,CAAC,QAAQ,GAAG,CAAC;IACtB;AACF;AAEA;AACA;AACA;AACA;AACA;AACA,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,KAAK,SAAS,EAAE;AACpC,IAAA,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,KAAI;AACrB,QAAA,OAAO,CAAC,KAAK,CAAC,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC;AAC7D,QAAA,OAAO,CAAC,QAAQ,GAAG,CAAC;AACtB,IAAA,CAAC,CAAC;AACJ;;;;"}
|
|
1
|
+
{"version":3,"file":"bin.js","sources":["../src/discoverArtifacts.ts","../src/injectDebugId.ts","../src/resolveRelease.ts","../src/uploadSourceMap.ts","../src/processSourceMaps.ts","../src/bin.ts"],"sourcesContent":["// packages/cli/src/discoverArtifacts.ts\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Artifact {\n jsPath: string\n mapPath: string\n}\n\nconst SOURCE_MAPPING_URL = /^\\s*\\/\\/#\\s*sourceMappingURL=(\\S+)\\s*$/gm\n\n// Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit\n// ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's \"type\") — all three\n// show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e\n// test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real\n// `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and\n// unstripped even though `.output/` itself was already fully written by the time discovery ran.\nconst JS_EXTENSIONS = ['.js', '.mjs', '.cjs']\n\n/** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its\n * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the\n * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,\n * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no\n * resolvable map either way is skipped. */\nexport function discoverArtifacts(directory: string): Artifact[] {\n const artifacts: Artifact[] = []\n walk(directory, artifacts)\n return artifacts\n}\n\nfunction walk(dir: string, artifacts: Artifact[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n walk(fullPath, artifacts)\n } else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {\n const mapPath = resolveMapPath(fullPath)\n if (mapPath) artifacts.push({ jsPath: fullPath, mapPath })\n }\n }\n}\n\nfunction resolveMapPath(jsPath: string): string | undefined {\n const commentMapPath = readSourceMappingUrlComment(jsPath)\n if (commentMapPath && existsSync(commentMapPath)) return commentMapPath\n\n const fallbackMapPath = `${jsPath}.map`\n if (existsSync(fallbackMapPath)) return fallbackMapPath\n\n return undefined\n}\n\nfunction readSourceMappingUrlComment(jsPath: string): string | undefined {\n let content: string\n try {\n content = readFileSync(jsPath, 'utf8')\n } catch {\n // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it\n // like \"no comment found\" rather than aborting the whole discoverArtifacts() walk.\n return undefined\n }\n\n const matches = [...content.matchAll(SOURCE_MAPPING_URL)]\n if (matches.length === 0) return undefined\n\n // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat\n // concatenated/reprocessed output — later comments supersede earlier ones.\n const reference = matches.at(-1)![1]\n if (reference.startsWith('data:')) return undefined // embedded map, nothing to discover on disk\n\n return join(dirname(jsPath), reference)\n}\n","// packages/cli/src/injectDebugId.ts\n\nexport interface InjectedArtifact {\n js: string\n map: string\n}\n\n/** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in\n * memory — callers decide whether/when to persist the result to disk (processSourceMaps\n * only writes it after a successful upload, so a failed upload never leaves partially\n * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)\n * removed, since the source map it names is only ever kept in GetMonitor's backend after\n * a successful upload — never served publicly alongside it.\n *\n * `originalMapJson` must be valid JSON — this is a pure function with no fallback to\n * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's\n * caller expects a definite result), so a malformed map is left to throw via JSON.parse\n * rather than being swallowed here. */\nexport function injectDebugId(originalJs: string, originalMapJson: string, debugId: string): InjectedArtifact {\n const withoutMapComment = originalJs\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))\n .join('\\n')\n\n const map = JSON.parse(originalMapJson)\n map.debugId = debugId\n\n return {\n js: `${withoutMapComment}\\n${buildInjectedSnippet(debugId)}`,\n map: JSON.stringify(map),\n }\n}\n\n/** At load time, captures this statement's own `Error().stack`, extracts this file's\n * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for\n * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's\n * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,\n * it scans every stack line and takes the first one that matches any of those shapes, rather\n * than assuming a fixed line index — V8 prefixes an `\"ErrorType: message\"` header line that\n * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong\n * file's identity) on non-V8 engines; the header line simply fails to match any frame regex\n * and is skipped automatically. A later real error whose frame.filename is parsed from the\n * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any\n * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak\n * into the file's module scope.\n *\n * `debugId` is interpolated unescaped into the generated snippet's string literal. That's\n * safe today because every caller in this system sources `debugId` from\n * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but\n * this function itself doesn't enforce that shape, so a caller passing an arbitrary string\n * containing `'` or `\\` would produce invalid/injected JS here. Flagged, not fixed, since\n * validating/escaping isn't part of this function's specified contract. */\nfunction buildInjectedSnippet(debugId: string): string {\n return (\n \";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\\\n');var m=null;\" +\n 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +\n \"m=l.match(/\\\\((.*):(\\\\d+):(\\\\d+)\\\\)\\\\s*$/)||l.match(/at (.*):(\\\\d+):(\\\\d+)\\\\s*$/)||l.match(/@(.*):(\\\\d+):(\\\\d+)\\\\s*$/)}\" +\n \"var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);\" +\n `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +\n '}}catch(e){}})();'\n )\n}\n","// packages/cli/src/resolveRelease.ts\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit\n * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside\n * a git working tree) -> `version` field of the nearest package.json walking up from\n * `directory`. Matches the SDKs' own optional `release` field so events and source maps\n * for the same deploy carry the same value. */\nexport function resolveRelease(directory: string, explicit?: string): string {\n if (explicit) return explicit\n if (process.env.GETMONITOR_RELEASE) return process.env.GETMONITOR_RELEASE\n\n const gitSha = tryGitSha(directory)\n if (gitSha) return gitSha\n\n const packageVersion = tryPackageVersion(directory)\n if (packageVersion) return packageVersion\n\n throw new Error(\n 'Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a \"version\" field.',\n )\n}\n\nfunction tryGitSha(directory: string): string | undefined {\n try {\n return execFileSync('git', ['rev-parse', 'HEAD'], {\n cwd: directory,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim()\n } catch {\n return undefined\n }\n}\n\nfunction tryPackageVersion(directory: string): string | undefined {\n let dir = directory\n for (let i = 0; i < 20; i++) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n return typeof pkg.version === 'string' ? pkg.version : undefined\n } catch {\n return undefined\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n return undefined\n}\n","// packages/cli/src/uploadSourceMap.ts\n\n/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */\nexport const DEFAULT_API_HOST = 'https://track.getmonitor.io'\n\nexport interface UploadSourceMapParams {\n /**\n * @internal Test-only override for redirecting delivery to a local mock server (see\n * cli/e2e/processSourceMaps.spec.ts and the nextjs-config/nuxt e2e suites). Never exposed\n * through the public CLI/programmatic surface — real usage always ships to\n * {@link DEFAULT_API_HOST}.\n */\n apiHost?: string\n authToken: string\n release: string\n debugId: string\n filename: string\n mapContent: string\n fetchImpl?: typeof fetch\n}\n\n/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.\n * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides\n * what \"failed\" means for its own result reporting and disk-write ordering. */\nexport async function uploadSourceMap(params: UploadSourceMapParams): Promise<void> {\n // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native\n // fetch() throws \"Illegal invocation\" if called with a `this` other than\n // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below\n // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this\n // bind is defensive/consistent rather than load-bearing for this particular call site — but\n // keeping the same default expression as HttpTransport avoids a divergent default if this\n // code is ever refactored into a method.\n const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis)\n const apiHost = params.apiHost ?? DEFAULT_API_HOST\n\n const form = new FormData()\n form.set('release', params.release)\n form.set('debugId', params.debugId)\n form.set('filename', params.filename)\n form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`)\n\n const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${params.authToken}` },\n body: form,\n })\n\n if (!response.ok) {\n // Deliberately excludes `params.filename` — a real deployment can have hundreds/thousands\n // of artifacts fail identically (e.g. one bad auth token), and processSourceMaps\n // deduplicates these messages to log the reason once instead of once per file. Baking the\n // filename in here would make every message unique and defeat that dedup.\n throw new Error(`${response.status} ${response.statusText}`)\n }\n}\n","// packages/cli/src/processSourceMaps.ts\nimport { randomUUID } from 'node:crypto'\nimport { readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { relative } from 'node:path'\nimport { discoverArtifacts } from './discoverArtifacts'\nimport { injectDebugId, InjectedArtifact } from './injectDebugId'\nimport { resolveRelease } from './resolveRelease'\nimport { uploadSourceMap } from './uploadSourceMap'\nimport { ProcessSourceMapsOptions, ProcessSourceMapsResult } from './types'\n\n/**\n * @internal Test-only host override, intersected into `processSourceMaps`'s options but\n * deliberately not part of the exported `ProcessSourceMapsOptions` type — see\n * `uploadSourceMap`'s `UploadSourceMapParams.apiHost`. Used by this package's own e2e suite\n * and by nextjs-config/nuxt's e2e suites (via their own internal overrides) to redirect\n * delivery to a local mock server; real callers must never set it.\n */\ninterface InternalTestOverrides {\n apiHost?: string\n}\n\n/** Number of artifacts uploaded at once. Each upload is an independent network round trip to\n * ingester-api, so processing them one at a time made wall-clock time scale linearly with\n * artifact count for no reason — a real Next.js build can emit well over a thousand of them,\n * turning a few hundred ms of per-file latency into many minutes of serial waiting. */\nconst UPLOAD_CONCURRENCY = 20\n\n/** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a\n * debug ID, uploads the tagged source map, and — only on a successful upload — writes the\n * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload\n * fails is left completely untouched on disk, so it can be retried by re-running this\n * function against the same directory. Artifacts are uploaded concurrently (bounded by\n * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match\n * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */\nexport async function processSourceMaps(\n options: ProcessSourceMapsOptions & InternalTestOverrides\n): Promise<ProcessSourceMapsResult> {\n const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN\n if (!authToken) {\n throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.')\n }\n\n const release = resolveRelease(options.directory, options.release)\n const artifacts = discoverArtifacts(options.directory)\n // Indexed by each artifact's position in `artifacts` rather than appended in completion\n // order, so the final result below is deterministic no matter which worker finishes first.\n type Outcome =\n | { path: string; kind: 'uploaded' }\n | { path: string; kind: 'failed' }\n | { path: string; kind: 'skipped'; reason: string }\n const outcomes: Outcome[] = new Array(artifacts.length)\n\n const processOne = async (index: number): Promise<void> => {\n const artifact = artifacts[index]\n const debugId = randomUUID()\n let injected: InjectedArtifact\n\n // Local step: reading the artifact and injecting its debug ID. A failure here (unreadable\n // file, malformed map JSON) means the build's own output is broken — that's a real bug\n // worth failing CI over, so it's tracked in `failed` and logged per-file: with a genuine\n // local bug there are normally only one or a handful of these, unlike a systemic upload\n // outage below.\n try {\n const originalJs = readFileSync(artifact.jsPath, 'utf8')\n const originalMap = readFileSync(artifact.mapPath, 'utf8')\n // injectDebugId is a pure function that throws on malformed map JSON (by design — see\n // its own doc comment). One corrupt/unreadable artifact on disk must not abort\n // processing of every other artifact in the directory, the same failure-isolation\n // principle discoverArtifacts applies to unreadable files during its walk. Nothing has\n // been uploaded or written yet at this point, so a thrown injectDebugId failure leaves\n // the artifact's files completely untouched, and it's safe to report it as `failed` for\n // a retry.\n injected = injectDebugId(originalJs, originalMap, debugId)\n } catch (error) {\n console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error)\n outcomes[index] = { path: artifact.jsPath, kind: 'failed' }\n return\n }\n\n // Remote step: uploading to the ingest API. Unlike the local step above, this artifact was\n // perfectly fine — the *endpoint* rejected the request or was unreachable (bad/expired auth\n // token, network outage, backend 5xx). That's an infra/connectivity problem outside this\n // build's control, not a bug in it, so it's tracked separately in `skipped` (never `failed`)\n // and deliberately NOT logged per-file here: an outage or bad token fails every one of\n // potentially thousands of artifacts identically, and logging each one would drown out\n // everything else in the build's output. The deduplicated reason is logged once, after all\n // artifacts finish, by the summary block below.\n try {\n await uploadSourceMap({\n apiHost: options.apiHost,\n authToken,\n release,\n debugId,\n // Relative to options.directory, not the absolute on-disk path — the backend has no\n // use for (and shouldn't see) the build machine's local filesystem layout.\n filename: relative(options.directory, artifact.jsPath),\n mapContent: injected.map,\n fetchImpl: options.fetchImpl,\n })\n } catch (error) {\n outcomes[index] = {\n path: artifact.jsPath,\n kind: 'skipped',\n reason: error instanceof Error ? error.message : String(error),\n }\n return\n }\n\n try {\n writeFileSync(artifact.jsPath, injected.js)\n rmSync(artifact.mapPath)\n outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' }\n } catch (cleanupError) {\n // The upload above already succeeded, so this must never land in `failed` or `skipped` —\n // a caller retrying either would mint a fresh debugId and re-upload, orphaning this\n // upload server-side under the old one with no way to reconcile the two. The local\n // cleanup failure (disk full, permission error, file lock) is real and worth knowing\n // about, so it's surfaced here rather than silently swallowed, but it doesn't change\n // the artifact's outcome.\n outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' }\n console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError)\n }\n }\n\n // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared\n // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.\n let nextIndex = 0\n const runWorker = async (): Promise<void> => {\n while (nextIndex < artifacts.length) {\n const index = nextIndex++\n await processOne(index)\n }\n }\n const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length)\n await Promise.all(Array.from({ length: workerCount }, runWorker))\n\n const result: ProcessSourceMapsResult = { uploaded: [], failed: [], skipped: [] }\n // Counts occurrences of each distinct skip reason, preserving first-seen order, so the\n // summary below reads one line per *kind* of problem rather than one line per file.\n const skipReasonCounts = new Map<string, number>()\n for (const outcome of outcomes) {\n if (outcome.kind === 'uploaded') result.uploaded.push(outcome.path)\n else if (outcome.kind === 'failed') result.failed.push(outcome.path)\n else {\n result.skipped.push(outcome.path)\n skipReasonCounts.set(outcome.reason, (skipReasonCounts.get(outcome.reason) ?? 0) + 1)\n }\n }\n\n if (result.skipped.length > 0) {\n console.warn(`GetMonitor: could not upload ${result.skipped.length} source map(s); continuing without them.`)\n for (const [reason, count] of skipReasonCounts) {\n console.warn(` - ${reason} (${count}x)`)\n }\n }\n\n return result\n}\n","// packages/cli/src/bin.ts\nimport { processSourceMaps } from './processSourceMaps'\n\ninterface ParsedArgs {\n directory: string\n release?: string\n authToken?: string\n}\n\n/** Exported (not just used internally) so it's unit-testable without spawning a process. */\nexport function parseArgs(argv: string[]): ParsedArgs {\n const [command, subcommand, directory, ...rest] = argv\n if (command !== 'sourcemaps' || subcommand !== 'upload' || !directory) {\n throw new Error(\n 'Usage: getmonitor sourcemaps upload <directory> [--release <release>] [--auth-token <token>]',\n )\n }\n\n let release: string | undefined\n let authToken: string | undefined\n\n for (let i = 0; i < rest.length; i += 2) {\n const flag = rest[i]\n const value = rest[i + 1]\n if (flag === '--release') release = value\n else if (flag === '--auth-token') authToken = value\n else throw new Error(`Unknown flag: ${flag}`)\n }\n\n return { directory, release, authToken }\n}\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2))\n\n const result = await processSourceMaps({\n directory: args.directory,\n release: args.release,\n authToken: args.authToken,\n })\n\n console.log(`Uploaded ${result.uploaded.length} source map(s).`)\n if (result.skipped.length > 0) {\n // Non-fatal by design: processSourceMaps already warned with the reason(s) above. This is\n // a plain summary line, not an error — exitCode must stay 0 when the only problem was an\n // unreachable/unauthenticated upload endpoint, not a bug in this build's output, so a\n // `next build && getmonitor sourcemaps upload` pipeline still succeeds overall.\n console.log(`Skipped ${result.skipped.length} source map(s) due to upload errors (see warnings above).`)\n }\n if (result.failed.length > 0) {\n console.error(`Failed to upload ${result.failed.length} source map(s):`)\n for (const file of result.failed) console.error(` ${file}`)\n process.exitCode = 1\n }\n}\n\n// Skipped under Vitest (which imports this module to test parseArgs) — only run when\n// invoked directly as the built dist/bin.js executable. Confirmed empirically that Vitest\n// sets process.env.VITEST = 'true' in the process that loads this module, so this check\n// reliably prevents main() (which does real I/O and can set process.exitCode) from running\n// during `pnpm test`.\nif (process.env.VITEST === undefined) {\n main().catch((error) => {\n console.error(error instanceof Error ? error.message : error)\n process.exitCode = 1\n })\n}\n"],"names":[],"mappings":";;;;;;AAAA;AASA,MAAM,kBAAkB,GAAG,0CAA0C;AAErE;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;AAE7C;;;;AAI2C;AACrC,SAAU,iBAAiB,CAAC,SAAiB,EAAA;IACjD,MAAM,SAAS,GAAe,EAAE;AAChC,IAAA,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC;AAC1B,IAAA,OAAO,SAAS;AAClB;AAEA,SAAS,IAAI,CAAC,GAAW,EAAE,SAAqB,EAAA;AAC9C,IAAA,KAAK,MAAM,KAAK,IAAI,WAAW,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,EAAE;QAC7D,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC;AACtC,QAAA,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE;AACvB,YAAA,IAAI,CAAC,QAAQ,EAAE,SAAS,CAAC;QAC3B;aAAO,IAAI,KAAK,CAAC,MAAM,EAAE,IAAI,aAAa,CAAC,IAAI,CAAC,CAAC,GAAG,KAAK,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE;AAClF,YAAA,MAAM,OAAO,GAAG,cAAc,CAAC,QAAQ,CAAC;AACxC,YAAA,IAAI,OAAO;gBAAE,SAAS,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,QAA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O,CAAC,KAAK,CAAC,KAAK,IAAI,CAAA,CAAE,CAAC;AAC5D,QAAA,OAAO,CAAC,QAAQ,GAAG,CAAC;IACtB;AACF;AAEA;AACA;AACA;AACA;AACA;AACA,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,KAAK,SAAS,EAAE;AACpC,IAAA,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,KAAI;AACrB,QAAA,OAAO,CAAC,KAAK,CAAC,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC;AAC7D,QAAA,OAAO,CAAC,QAAQ,GAAG,CAAC;AACtB,IAAA,CAAC,CAAC;AACJ;;;;"}
|
package/dist/index.cjs
CHANGED
|
@@ -173,7 +173,7 @@ function tryPackageVersion(directory) {
|
|
|
173
173
|
|
|
174
174
|
// packages/cli/src/uploadSourceMap.ts
|
|
175
175
|
/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */
|
|
176
|
-
const DEFAULT_API_HOST = 'https://
|
|
176
|
+
const DEFAULT_API_HOST = 'https://track.getmonitor.io';
|
|
177
177
|
/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.
|
|
178
178
|
* Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides
|
|
179
179
|
* what "failed" means for its own result reporting and disk-write ordering. */
|
|
@@ -198,7 +198,11 @@ async function uploadSourceMap(params) {
|
|
|
198
198
|
body: form,
|
|
199
199
|
});
|
|
200
200
|
if (!response.ok) {
|
|
201
|
-
|
|
201
|
+
// Deliberately excludes `params.filename` — a real deployment can have hundreds/thousands
|
|
202
|
+
// of artifacts fail identically (e.g. one bad auth token), and processSourceMaps
|
|
203
|
+
// deduplicates these messages to log the reason once instead of once per file. Baking the
|
|
204
|
+
// filename in here would make every message unique and defeat that dedup.
|
|
205
|
+
throw new Error(`${response.status} ${response.statusText}`);
|
|
202
206
|
}
|
|
203
207
|
}
|
|
204
208
|
|
|
@@ -222,24 +226,42 @@ async function processSourceMaps(options) {
|
|
|
222
226
|
}
|
|
223
227
|
const release = resolveRelease(options.directory, options.release);
|
|
224
228
|
const artifacts = discoverArtifacts(options.directory);
|
|
225
|
-
// Indexed by each artifact's position in `artifacts` rather than appended in completion
|
|
226
|
-
// order, so the final result below is deterministic no matter which worker finishes first.
|
|
227
229
|
const outcomes = new Array(artifacts.length);
|
|
228
230
|
const processOne = async (index) => {
|
|
229
231
|
const artifact = artifacts[index];
|
|
230
232
|
const debugId = node_crypto.randomUUID();
|
|
231
233
|
let injected;
|
|
234
|
+
// Local step: reading the artifact and injecting its debug ID. A failure here (unreadable
|
|
235
|
+
// file, malformed map JSON) means the build's own output is broken — that's a real bug
|
|
236
|
+
// worth failing CI over, so it's tracked in `failed` and logged per-file: with a genuine
|
|
237
|
+
// local bug there are normally only one or a handful of these, unlike a systemic upload
|
|
238
|
+
// outage below.
|
|
232
239
|
try {
|
|
233
240
|
const originalJs = node_fs.readFileSync(artifact.jsPath, 'utf8');
|
|
234
241
|
const originalMap = node_fs.readFileSync(artifact.mapPath, 'utf8');
|
|
235
242
|
// injectDebugId is a pure function that throws on malformed map JSON (by design — see
|
|
236
|
-
// its own doc comment).
|
|
237
|
-
//
|
|
238
|
-
//
|
|
239
|
-
//
|
|
240
|
-
//
|
|
241
|
-
//
|
|
243
|
+
// its own doc comment). One corrupt/unreadable artifact on disk must not abort
|
|
244
|
+
// processing of every other artifact in the directory, the same failure-isolation
|
|
245
|
+
// principle discoverArtifacts applies to unreadable files during its walk. Nothing has
|
|
246
|
+
// been uploaded or written yet at this point, so a thrown injectDebugId failure leaves
|
|
247
|
+
// the artifact's files completely untouched, and it's safe to report it as `failed` for
|
|
248
|
+
// a retry.
|
|
242
249
|
injected = injectDebugId(originalJs, originalMap, debugId);
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error);
|
|
253
|
+
outcomes[index] = { path: artifact.jsPath, kind: 'failed' };
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
// Remote step: uploading to the ingest API. Unlike the local step above, this artifact was
|
|
257
|
+
// perfectly fine — the *endpoint* rejected the request or was unreachable (bad/expired auth
|
|
258
|
+
// token, network outage, backend 5xx). That's an infra/connectivity problem outside this
|
|
259
|
+
// build's control, not a bug in it, so it's tracked separately in `skipped` (never `failed`)
|
|
260
|
+
// and deliberately NOT logged per-file here: an outage or bad token fails every one of
|
|
261
|
+
// potentially thousands of artifacts identically, and logging each one would drown out
|
|
262
|
+
// everything else in the build's output. The deduplicated reason is logged once, after all
|
|
263
|
+
// artifacts finish, by the summary block below.
|
|
264
|
+
try {
|
|
243
265
|
await uploadSourceMap({
|
|
244
266
|
apiHost: options.apiHost,
|
|
245
267
|
authToken,
|
|
@@ -253,27 +275,26 @@ async function processSourceMaps(options) {
|
|
|
253
275
|
});
|
|
254
276
|
}
|
|
255
277
|
catch (error) {
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
outcomes[index] = { path: artifact.jsPath, ok: false };
|
|
278
|
+
outcomes[index] = {
|
|
279
|
+
path: artifact.jsPath,
|
|
280
|
+
kind: 'skipped',
|
|
281
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
282
|
+
};
|
|
262
283
|
return;
|
|
263
284
|
}
|
|
264
285
|
try {
|
|
265
286
|
node_fs.writeFileSync(artifact.jsPath, injected.js);
|
|
266
287
|
node_fs.rmSync(artifact.mapPath);
|
|
267
|
-
outcomes[index] = { path: artifact.jsPath,
|
|
288
|
+
outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' };
|
|
268
289
|
}
|
|
269
290
|
catch (cleanupError) {
|
|
270
|
-
// The upload above already succeeded, so this must never land in `failed`
|
|
271
|
-
// retrying
|
|
291
|
+
// The upload above already succeeded, so this must never land in `failed` or `skipped` —
|
|
292
|
+
// a caller retrying either would mint a fresh debugId and re-upload, orphaning this
|
|
272
293
|
// upload server-side under the old one with no way to reconcile the two. The local
|
|
273
294
|
// cleanup failure (disk full, permission error, file lock) is real and worth knowing
|
|
274
295
|
// about, so it's surfaced here rather than silently swallowed, but it doesn't change
|
|
275
296
|
// the artifact's outcome.
|
|
276
|
-
outcomes[index] = { path: artifact.jsPath,
|
|
297
|
+
outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' };
|
|
277
298
|
console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError);
|
|
278
299
|
}
|
|
279
300
|
};
|
|
@@ -288,9 +309,25 @@ async function processSourceMaps(options) {
|
|
|
288
309
|
};
|
|
289
310
|
const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length);
|
|
290
311
|
await Promise.all(Array.from({ length: workerCount }, runWorker));
|
|
291
|
-
const result = { uploaded: [], failed: [] };
|
|
312
|
+
const result = { uploaded: [], failed: [], skipped: [] };
|
|
313
|
+
// Counts occurrences of each distinct skip reason, preserving first-seen order, so the
|
|
314
|
+
// summary below reads one line per *kind* of problem rather than one line per file.
|
|
315
|
+
const skipReasonCounts = new Map();
|
|
292
316
|
for (const outcome of outcomes) {
|
|
293
|
-
(outcome.
|
|
317
|
+
if (outcome.kind === 'uploaded')
|
|
318
|
+
result.uploaded.push(outcome.path);
|
|
319
|
+
else if (outcome.kind === 'failed')
|
|
320
|
+
result.failed.push(outcome.path);
|
|
321
|
+
else {
|
|
322
|
+
result.skipped.push(outcome.path);
|
|
323
|
+
skipReasonCounts.set(outcome.reason, (skipReasonCounts.get(outcome.reason) ?? 0) + 1);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (result.skipped.length > 0) {
|
|
327
|
+
console.warn(`GetMonitor: could not upload ${result.skipped.length} source map(s); continuing without them.`);
|
|
328
|
+
for (const [reason, count] of skipReasonCounts) {
|
|
329
|
+
console.warn(` - ${reason} (${count}x)`);
|
|
330
|
+
}
|
|
294
331
|
}
|
|
295
332
|
return result;
|
|
296
333
|
}
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/discoverArtifacts.ts","../src/injectDebugId.ts","../src/resolveRelease.ts","../src/uploadSourceMap.ts","../src/processSourceMaps.ts"],"sourcesContent":["// packages/cli/src/discoverArtifacts.ts\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Artifact {\n jsPath: string\n mapPath: string\n}\n\nconst SOURCE_MAPPING_URL = /^\\s*\\/\\/#\\s*sourceMappingURL=(\\S+)\\s*$/gm\n\n// Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit\n// ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's \"type\") — all three\n// show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e\n// test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real\n// `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and\n// unstripped even though `.output/` itself was already fully written by the time discovery ran.\nconst JS_EXTENSIONS = ['.js', '.mjs', '.cjs']\n\n/** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its\n * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the\n * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,\n * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no\n * resolvable map either way is skipped. */\nexport function discoverArtifacts(directory: string): Artifact[] {\n const artifacts: Artifact[] = []\n walk(directory, artifacts)\n return artifacts\n}\n\nfunction walk(dir: string, artifacts: Artifact[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n walk(fullPath, artifacts)\n } else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {\n const mapPath = resolveMapPath(fullPath)\n if (mapPath) artifacts.push({ jsPath: fullPath, mapPath })\n }\n }\n}\n\nfunction resolveMapPath(jsPath: string): string | undefined {\n const commentMapPath = readSourceMappingUrlComment(jsPath)\n if (commentMapPath && existsSync(commentMapPath)) return commentMapPath\n\n const fallbackMapPath = `${jsPath}.map`\n if (existsSync(fallbackMapPath)) return fallbackMapPath\n\n return undefined\n}\n\nfunction readSourceMappingUrlComment(jsPath: string): string | undefined {\n let content: string\n try {\n content = readFileSync(jsPath, 'utf8')\n } catch {\n // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it\n // like \"no comment found\" rather than aborting the whole discoverArtifacts() walk.\n return undefined\n }\n\n const matches = [...content.matchAll(SOURCE_MAPPING_URL)]\n if (matches.length === 0) return undefined\n\n // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat\n // concatenated/reprocessed output — later comments supersede earlier ones.\n const reference = matches.at(-1)![1]\n if (reference.startsWith('data:')) return undefined // embedded map, nothing to discover on disk\n\n return join(dirname(jsPath), reference)\n}\n","// packages/cli/src/injectDebugId.ts\n\nexport interface InjectedArtifact {\n js: string\n map: string\n}\n\n/** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in\n * memory — callers decide whether/when to persist the result to disk (processSourceMaps\n * only writes it after a successful upload, so a failed upload never leaves partially\n * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)\n * removed, since the source map it names is only ever kept in GetMonitor's backend after\n * a successful upload — never served publicly alongside it.\n *\n * `originalMapJson` must be valid JSON — this is a pure function with no fallback to\n * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's\n * caller expects a definite result), so a malformed map is left to throw via JSON.parse\n * rather than being swallowed here. */\nexport function injectDebugId(originalJs: string, originalMapJson: string, debugId: string): InjectedArtifact {\n const withoutMapComment = originalJs\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))\n .join('\\n')\n\n const map = JSON.parse(originalMapJson)\n map.debugId = debugId\n\n return {\n js: `${withoutMapComment}\\n${buildInjectedSnippet(debugId)}`,\n map: JSON.stringify(map),\n }\n}\n\n/** At load time, captures this statement's own `Error().stack`, extracts this file's\n * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for\n * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's\n * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,\n * it scans every stack line and takes the first one that matches any of those shapes, rather\n * than assuming a fixed line index — V8 prefixes an `\"ErrorType: message\"` header line that\n * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong\n * file's identity) on non-V8 engines; the header line simply fails to match any frame regex\n * and is skipped automatically. A later real error whose frame.filename is parsed from the\n * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any\n * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak\n * into the file's module scope.\n *\n * `debugId` is interpolated unescaped into the generated snippet's string literal. That's\n * safe today because every caller in this system sources `debugId` from\n * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but\n * this function itself doesn't enforce that shape, so a caller passing an arbitrary string\n * containing `'` or `\\` would produce invalid/injected JS here. Flagged, not fixed, since\n * validating/escaping isn't part of this function's specified contract. */\nfunction buildInjectedSnippet(debugId: string): string {\n return (\n \";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\\\n');var m=null;\" +\n 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +\n \"m=l.match(/\\\\((.*):(\\\\d+):(\\\\d+)\\\\)\\\\s*$/)||l.match(/at (.*):(\\\\d+):(\\\\d+)\\\\s*$/)||l.match(/@(.*):(\\\\d+):(\\\\d+)\\\\s*$/)}\" +\n \"var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);\" +\n `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +\n '}}catch(e){}})();'\n )\n}\n","// packages/cli/src/resolveRelease.ts\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit\n * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside\n * a git working tree) -> `version` field of the nearest package.json walking up from\n * `directory`. Matches the SDKs' own optional `release` field so events and source maps\n * for the same deploy carry the same value. */\nexport function resolveRelease(directory: string, explicit?: string): string {\n if (explicit) return explicit\n if (process.env.GETMONITOR_RELEASE) return process.env.GETMONITOR_RELEASE\n\n const gitSha = tryGitSha(directory)\n if (gitSha) return gitSha\n\n const packageVersion = tryPackageVersion(directory)\n if (packageVersion) return packageVersion\n\n throw new Error(\n 'Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a \"version\" field.',\n )\n}\n\nfunction tryGitSha(directory: string): string | undefined {\n try {\n return execFileSync('git', ['rev-parse', 'HEAD'], {\n cwd: directory,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim()\n } catch {\n return undefined\n }\n}\n\nfunction tryPackageVersion(directory: string): string | undefined {\n let dir = directory\n for (let i = 0; i < 20; i++) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n return typeof pkg.version === 'string' ? pkg.version : undefined\n } catch {\n return undefined\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n return undefined\n}\n","// packages/cli/src/uploadSourceMap.ts\n\n/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */\nexport const DEFAULT_API_HOST = 'https://ingest.getmonitor.io'\n\nexport interface UploadSourceMapParams {\n /**\n * @internal Test-only override for redirecting delivery to a local mock server (see\n * cli/e2e/processSourceMaps.spec.ts and the nextjs-config/nuxt e2e suites). Never exposed\n * through the public CLI/programmatic surface — real usage always ships to\n * {@link DEFAULT_API_HOST}.\n */\n apiHost?: string\n authToken: string\n release: string\n debugId: string\n filename: string\n mapContent: string\n fetchImpl?: typeof fetch\n}\n\n/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.\n * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides\n * what \"failed\" means for its own result reporting and disk-write ordering. */\nexport async function uploadSourceMap(params: UploadSourceMapParams): Promise<void> {\n // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native\n // fetch() throws \"Illegal invocation\" if called with a `this` other than\n // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below\n // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this\n // bind is defensive/consistent rather than load-bearing for this particular call site — but\n // keeping the same default expression as HttpTransport avoids a divergent default if this\n // code is ever refactored into a method.\n const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis)\n const apiHost = params.apiHost ?? DEFAULT_API_HOST\n\n const form = new FormData()\n form.set('release', params.release)\n form.set('debugId', params.debugId)\n form.set('filename', params.filename)\n form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`)\n\n const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${params.authToken}` },\n body: form,\n })\n\n if (!response.ok) {\n throw new Error(`Source map upload failed for ${params.filename}: ${response.status} ${response.statusText}`)\n }\n}\n","// packages/cli/src/processSourceMaps.ts\nimport { randomUUID } from 'node:crypto'\nimport { readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { relative } from 'node:path'\nimport { discoverArtifacts } from './discoverArtifacts'\nimport { injectDebugId, InjectedArtifact } from './injectDebugId'\nimport { resolveRelease } from './resolveRelease'\nimport { uploadSourceMap } from './uploadSourceMap'\nimport { ProcessSourceMapsOptions, ProcessSourceMapsResult } from './types'\n\n/**\n * @internal Test-only host override, intersected into `processSourceMaps`'s options but\n * deliberately not part of the exported `ProcessSourceMapsOptions` type — see\n * `uploadSourceMap`'s `UploadSourceMapParams.apiHost`. Used by this package's own e2e suite\n * and by nextjs-config/nuxt's e2e suites (via their own internal overrides) to redirect\n * delivery to a local mock server; real callers must never set it.\n */\ninterface InternalTestOverrides {\n apiHost?: string\n}\n\n/** Number of artifacts uploaded at once. Each upload is an independent network round trip to\n * ingester-api, so processing them one at a time made wall-clock time scale linearly with\n * artifact count for no reason — a real Next.js build can emit well over a thousand of them,\n * turning a few hundred ms of per-file latency into many minutes of serial waiting. */\nconst UPLOAD_CONCURRENCY = 20\n\n/** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a\n * debug ID, uploads the tagged source map, and — only on a successful upload — writes the\n * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload\n * fails is left completely untouched on disk, so it can be retried by re-running this\n * function against the same directory. Artifacts are uploaded concurrently (bounded by\n * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match\n * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */\nexport async function processSourceMaps(\n options: ProcessSourceMapsOptions & InternalTestOverrides\n): Promise<ProcessSourceMapsResult> {\n const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN\n if (!authToken) {\n throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.')\n }\n\n const release = resolveRelease(options.directory, options.release)\n const artifacts = discoverArtifacts(options.directory)\n // Indexed by each artifact's position in `artifacts` rather than appended in completion\n // order, so the final result below is deterministic no matter which worker finishes first.\n const outcomes: Array<{ path: string; ok: boolean }> = new Array(artifacts.length)\n\n const processOne = async (index: number): Promise<void> => {\n const artifact = artifacts[index]\n const debugId = randomUUID()\n let injected: InjectedArtifact\n\n try {\n const originalJs = readFileSync(artifact.jsPath, 'utf8')\n const originalMap = readFileSync(artifact.mapPath, 'utf8')\n // injectDebugId is a pure function that throws on malformed map JSON (by design — see\n // its own doc comment). That's deliberately caught here, alongside upload failures: one\n // corrupt/unreadable artifact on disk must not abort processing of every other artifact\n // in the directory, the same failure-isolation principle discoverArtifacts applies to\n // unreadable files during its walk. Nothing has been uploaded or written yet at this\n // point, so a thrown injectDebugId or upload failure leaves the artifact's files\n // completely untouched, and it's safe to report it as `failed` for a retry.\n injected = injectDebugId(originalJs, originalMap, debugId)\n\n await uploadSourceMap({\n apiHost: options.apiHost,\n authToken,\n release,\n debugId,\n // Relative to options.directory, not the absolute on-disk path — the backend has no\n // use for (and shouldn't see) the build machine's local filesystem layout.\n filename: relative(options.directory, artifact.jsPath),\n mapContent: injected.map,\n fetchImpl: options.fetchImpl,\n })\n } catch (error) {\n // Surfaced here rather than swallowed: this is the only place the actual failure reason\n // (injectDebugId's malformed-JSON error, or uploadSourceMap's `status statusText` message)\n // is available. Without logging it, callers only ever see a bare list of failed paths with\n // no way to tell an auth failure from a malformed map from a network error.\n console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error)\n outcomes[index] = { path: artifact.jsPath, ok: false }\n return\n }\n\n try {\n writeFileSync(artifact.jsPath, injected.js)\n rmSync(artifact.mapPath)\n outcomes[index] = { path: artifact.jsPath, ok: true }\n } catch (cleanupError) {\n // The upload above already succeeded, so this must never land in `failed` — a caller\n // retrying failed artifacts would mint a fresh debugId and re-upload, orphaning this\n // upload server-side under the old one with no way to reconcile the two. The local\n // cleanup failure (disk full, permission error, file lock) is real and worth knowing\n // about, so it's surfaced here rather than silently swallowed, but it doesn't change\n // the artifact's outcome.\n outcomes[index] = { path: artifact.jsPath, ok: true }\n console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError)\n }\n }\n\n // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared\n // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.\n let nextIndex = 0\n const runWorker = async (): Promise<void> => {\n while (nextIndex < artifacts.length) {\n const index = nextIndex++\n await processOne(index)\n }\n }\n const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length)\n await Promise.all(Array.from({ length: workerCount }, runWorker))\n\n const result: ProcessSourceMapsResult = { uploaded: [], failed: [] }\n for (const outcome of outcomes) {\n ;(outcome.ok ? result.uploaded : result.failed).push(outcome.path)\n }\n return result\n}\n"],"names":["readdirSync","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O,CAAC,KAAK,CAAC,CAAA,SAAA,EAAY,QAAQ,CAAC,MAAM,CAAA,kCAAA,CAAoC,EAAE,YAAY,CAAC;QAC9F;AACF,IAAA,CAAC;;;IAID,IAAI,SAAS,GAAG,CAAC;AACjB,IAAA,MAAM,SAAS,GAAG,YAA0B;AAC1C,QAAA,OAAO,SAAS,GAAG,SAAS,CAAC,MAAM,EAAE;AACnC,YAAA,MAAM,KAAK,GAAG,SAAS,EAAE;AACzB,YAAA,MAAM,UAAU,CAAC,KAAK,CAAC;QACzB;AACF,IAAA,CAAC;AACD,IAAA,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,kBAAkB,EAAE,SAAS,CAAC,MAAM,CAAC;AAClE,IAAA,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,SAAS,CAAC,CAAC;IAEjE,MAAM,MAAM,GAA4B,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE;AACpE,IAAA,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;QAC7B,CAAC,OAAO,CAAC,EAAE,GAAG,MAAM,CAAC,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IACpE;AACA,IAAA,OAAO,MAAM;AACf;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/discoverArtifacts.ts","../src/injectDebugId.ts","../src/resolveRelease.ts","../src/uploadSourceMap.ts","../src/processSourceMaps.ts"],"sourcesContent":["// packages/cli/src/discoverArtifacts.ts\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Artifact {\n jsPath: string\n mapPath: string\n}\n\nconst SOURCE_MAPPING_URL = /^\\s*\\/\\/#\\s*sourceMappingURL=(\\S+)\\s*$/gm\n\n// Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit\n// ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's \"type\") — all three\n// show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e\n// test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real\n// `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and\n// unstripped even though `.output/` itself was already fully written by the time discovery ran.\nconst JS_EXTENSIONS = ['.js', '.mjs', '.cjs']\n\n/** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its\n * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the\n * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,\n * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no\n * resolvable map either way is skipped. */\nexport function discoverArtifacts(directory: string): Artifact[] {\n const artifacts: Artifact[] = []\n walk(directory, artifacts)\n return artifacts\n}\n\nfunction walk(dir: string, artifacts: Artifact[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n walk(fullPath, artifacts)\n } else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {\n const mapPath = resolveMapPath(fullPath)\n if (mapPath) artifacts.push({ jsPath: fullPath, mapPath })\n }\n }\n}\n\nfunction resolveMapPath(jsPath: string): string | undefined {\n const commentMapPath = readSourceMappingUrlComment(jsPath)\n if (commentMapPath && existsSync(commentMapPath)) return commentMapPath\n\n const fallbackMapPath = `${jsPath}.map`\n if (existsSync(fallbackMapPath)) return fallbackMapPath\n\n return undefined\n}\n\nfunction readSourceMappingUrlComment(jsPath: string): string | undefined {\n let content: string\n try {\n content = readFileSync(jsPath, 'utf8')\n } catch {\n // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it\n // like \"no comment found\" rather than aborting the whole discoverArtifacts() walk.\n return undefined\n }\n\n const matches = [...content.matchAll(SOURCE_MAPPING_URL)]\n if (matches.length === 0) return undefined\n\n // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat\n // concatenated/reprocessed output — later comments supersede earlier ones.\n const reference = matches.at(-1)![1]\n if (reference.startsWith('data:')) return undefined // embedded map, nothing to discover on disk\n\n return join(dirname(jsPath), reference)\n}\n","// packages/cli/src/injectDebugId.ts\n\nexport interface InjectedArtifact {\n js: string\n map: string\n}\n\n/** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in\n * memory — callers decide whether/when to persist the result to disk (processSourceMaps\n * only writes it after a successful upload, so a failed upload never leaves partially\n * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)\n * removed, since the source map it names is only ever kept in GetMonitor's backend after\n * a successful upload — never served publicly alongside it.\n *\n * `originalMapJson` must be valid JSON — this is a pure function with no fallback to\n * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's\n * caller expects a definite result), so a malformed map is left to throw via JSON.parse\n * rather than being swallowed here. */\nexport function injectDebugId(originalJs: string, originalMapJson: string, debugId: string): InjectedArtifact {\n const withoutMapComment = originalJs\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))\n .join('\\n')\n\n const map = JSON.parse(originalMapJson)\n map.debugId = debugId\n\n return {\n js: `${withoutMapComment}\\n${buildInjectedSnippet(debugId)}`,\n map: JSON.stringify(map),\n }\n}\n\n/** At load time, captures this statement's own `Error().stack`, extracts this file's\n * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for\n * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's\n * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,\n * it scans every stack line and takes the first one that matches any of those shapes, rather\n * than assuming a fixed line index — V8 prefixes an `\"ErrorType: message\"` header line that\n * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong\n * file's identity) on non-V8 engines; the header line simply fails to match any frame regex\n * and is skipped automatically. A later real error whose frame.filename is parsed from the\n * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any\n * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak\n * into the file's module scope.\n *\n * `debugId` is interpolated unescaped into the generated snippet's string literal. That's\n * safe today because every caller in this system sources `debugId` from\n * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but\n * this function itself doesn't enforce that shape, so a caller passing an arbitrary string\n * containing `'` or `\\` would produce invalid/injected JS here. Flagged, not fixed, since\n * validating/escaping isn't part of this function's specified contract. */\nfunction buildInjectedSnippet(debugId: string): string {\n return (\n \";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\\\n');var m=null;\" +\n 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +\n \"m=l.match(/\\\\((.*):(\\\\d+):(\\\\d+)\\\\)\\\\s*$/)||l.match(/at (.*):(\\\\d+):(\\\\d+)\\\\s*$/)||l.match(/@(.*):(\\\\d+):(\\\\d+)\\\\s*$/)}\" +\n \"var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);\" +\n `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +\n '}}catch(e){}})();'\n )\n}\n","// packages/cli/src/resolveRelease.ts\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit\n * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside\n * a git working tree) -> `version` field of the nearest package.json walking up from\n * `directory`. Matches the SDKs' own optional `release` field so events and source maps\n * for the same deploy carry the same value. */\nexport function resolveRelease(directory: string, explicit?: string): string {\n if (explicit) return explicit\n if (process.env.GETMONITOR_RELEASE) return process.env.GETMONITOR_RELEASE\n\n const gitSha = tryGitSha(directory)\n if (gitSha) return gitSha\n\n const packageVersion = tryPackageVersion(directory)\n if (packageVersion) return packageVersion\n\n throw new Error(\n 'Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a \"version\" field.',\n )\n}\n\nfunction tryGitSha(directory: string): string | undefined {\n try {\n return execFileSync('git', ['rev-parse', 'HEAD'], {\n cwd: directory,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim()\n } catch {\n return undefined\n }\n}\n\nfunction tryPackageVersion(directory: string): string | undefined {\n let dir = directory\n for (let i = 0; i < 20; i++) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n return typeof pkg.version === 'string' ? pkg.version : undefined\n } catch {\n return undefined\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n return undefined\n}\n","// packages/cli/src/uploadSourceMap.ts\n\n/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */\nexport const DEFAULT_API_HOST = 'https://track.getmonitor.io'\n\nexport interface UploadSourceMapParams {\n /**\n * @internal Test-only override for redirecting delivery to a local mock server (see\n * cli/e2e/processSourceMaps.spec.ts and the nextjs-config/nuxt e2e suites). Never exposed\n * through the public CLI/programmatic surface — real usage always ships to\n * {@link DEFAULT_API_HOST}.\n */\n apiHost?: string\n authToken: string\n release: string\n debugId: string\n filename: string\n mapContent: string\n fetchImpl?: typeof fetch\n}\n\n/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.\n * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides\n * what \"failed\" means for its own result reporting and disk-write ordering. */\nexport async function uploadSourceMap(params: UploadSourceMapParams): Promise<void> {\n // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native\n // fetch() throws \"Illegal invocation\" if called with a `this` other than\n // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below\n // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this\n // bind is defensive/consistent rather than load-bearing for this particular call site — but\n // keeping the same default expression as HttpTransport avoids a divergent default if this\n // code is ever refactored into a method.\n const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis)\n const apiHost = params.apiHost ?? DEFAULT_API_HOST\n\n const form = new FormData()\n form.set('release', params.release)\n form.set('debugId', params.debugId)\n form.set('filename', params.filename)\n form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`)\n\n const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${params.authToken}` },\n body: form,\n })\n\n if (!response.ok) {\n // Deliberately excludes `params.filename` — a real deployment can have hundreds/thousands\n // of artifacts fail identically (e.g. one bad auth token), and processSourceMaps\n // deduplicates these messages to log the reason once instead of once per file. Baking the\n // filename in here would make every message unique and defeat that dedup.\n throw new Error(`${response.status} ${response.statusText}`)\n }\n}\n","// packages/cli/src/processSourceMaps.ts\nimport { randomUUID } from 'node:crypto'\nimport { readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { relative } from 'node:path'\nimport { discoverArtifacts } from './discoverArtifacts'\nimport { injectDebugId, InjectedArtifact } from './injectDebugId'\nimport { resolveRelease } from './resolveRelease'\nimport { uploadSourceMap } from './uploadSourceMap'\nimport { ProcessSourceMapsOptions, ProcessSourceMapsResult } from './types'\n\n/**\n * @internal Test-only host override, intersected into `processSourceMaps`'s options but\n * deliberately not part of the exported `ProcessSourceMapsOptions` type — see\n * `uploadSourceMap`'s `UploadSourceMapParams.apiHost`. Used by this package's own e2e suite\n * and by nextjs-config/nuxt's e2e suites (via their own internal overrides) to redirect\n * delivery to a local mock server; real callers must never set it.\n */\ninterface InternalTestOverrides {\n apiHost?: string\n}\n\n/** Number of artifacts uploaded at once. Each upload is an independent network round trip to\n * ingester-api, so processing them one at a time made wall-clock time scale linearly with\n * artifact count for no reason — a real Next.js build can emit well over a thousand of them,\n * turning a few hundred ms of per-file latency into many minutes of serial waiting. */\nconst UPLOAD_CONCURRENCY = 20\n\n/** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a\n * debug ID, uploads the tagged source map, and — only on a successful upload — writes the\n * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload\n * fails is left completely untouched on disk, so it can be retried by re-running this\n * function against the same directory. Artifacts are uploaded concurrently (bounded by\n * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match\n * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */\nexport async function processSourceMaps(\n options: ProcessSourceMapsOptions & InternalTestOverrides\n): Promise<ProcessSourceMapsResult> {\n const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN\n if (!authToken) {\n throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.')\n }\n\n const release = resolveRelease(options.directory, options.release)\n const artifacts = discoverArtifacts(options.directory)\n // Indexed by each artifact's position in `artifacts` rather than appended in completion\n // order, so the final result below is deterministic no matter which worker finishes first.\n type Outcome =\n | { path: string; kind: 'uploaded' }\n | { path: string; kind: 'failed' }\n | { path: string; kind: 'skipped'; reason: string }\n const outcomes: Outcome[] = new Array(artifacts.length)\n\n const processOne = async (index: number): Promise<void> => {\n const artifact = artifacts[index]\n const debugId = randomUUID()\n let injected: InjectedArtifact\n\n // Local step: reading the artifact and injecting its debug ID. A failure here (unreadable\n // file, malformed map JSON) means the build's own output is broken — that's a real bug\n // worth failing CI over, so it's tracked in `failed` and logged per-file: with a genuine\n // local bug there are normally only one or a handful of these, unlike a systemic upload\n // outage below.\n try {\n const originalJs = readFileSync(artifact.jsPath, 'utf8')\n const originalMap = readFileSync(artifact.mapPath, 'utf8')\n // injectDebugId is a pure function that throws on malformed map JSON (by design — see\n // its own doc comment). One corrupt/unreadable artifact on disk must not abort\n // processing of every other artifact in the directory, the same failure-isolation\n // principle discoverArtifacts applies to unreadable files during its walk. Nothing has\n // been uploaded or written yet at this point, so a thrown injectDebugId failure leaves\n // the artifact's files completely untouched, and it's safe to report it as `failed` for\n // a retry.\n injected = injectDebugId(originalJs, originalMap, debugId)\n } catch (error) {\n console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error)\n outcomes[index] = { path: artifact.jsPath, kind: 'failed' }\n return\n }\n\n // Remote step: uploading to the ingest API. Unlike the local step above, this artifact was\n // perfectly fine — the *endpoint* rejected the request or was unreachable (bad/expired auth\n // token, network outage, backend 5xx). That's an infra/connectivity problem outside this\n // build's control, not a bug in it, so it's tracked separately in `skipped` (never `failed`)\n // and deliberately NOT logged per-file here: an outage or bad token fails every one of\n // potentially thousands of artifacts identically, and logging each one would drown out\n // everything else in the build's output. The deduplicated reason is logged once, after all\n // artifacts finish, by the summary block below.\n try {\n await uploadSourceMap({\n apiHost: options.apiHost,\n authToken,\n release,\n debugId,\n // Relative to options.directory, not the absolute on-disk path — the backend has no\n // use for (and shouldn't see) the build machine's local filesystem layout.\n filename: relative(options.directory, artifact.jsPath),\n mapContent: injected.map,\n fetchImpl: options.fetchImpl,\n })\n } catch (error) {\n outcomes[index] = {\n path: artifact.jsPath,\n kind: 'skipped',\n reason: error instanceof Error ? error.message : String(error),\n }\n return\n }\n\n try {\n writeFileSync(artifact.jsPath, injected.js)\n rmSync(artifact.mapPath)\n outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' }\n } catch (cleanupError) {\n // The upload above already succeeded, so this must never land in `failed` or `skipped` —\n // a caller retrying either would mint a fresh debugId and re-upload, orphaning this\n // upload server-side under the old one with no way to reconcile the two. The local\n // cleanup failure (disk full, permission error, file lock) is real and worth knowing\n // about, so it's surfaced here rather than silently swallowed, but it doesn't change\n // the artifact's outcome.\n outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' }\n console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError)\n }\n }\n\n // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared\n // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.\n let nextIndex = 0\n const runWorker = async (): Promise<void> => {\n while (nextIndex < artifacts.length) {\n const index = nextIndex++\n await processOne(index)\n }\n }\n const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length)\n await Promise.all(Array.from({ length: workerCount }, runWorker))\n\n const result: ProcessSourceMapsResult = { uploaded: [], failed: [], skipped: [] }\n // Counts occurrences of each distinct skip reason, preserving first-seen order, so the\n // summary below reads one line per *kind* of problem rather than one line per file.\n const skipReasonCounts = new Map<string, number>()\n for (const outcome of outcomes) {\n if (outcome.kind === 'uploaded') result.uploaded.push(outcome.path)\n else if (outcome.kind === 'failed') result.failed.push(outcome.path)\n else {\n result.skipped.push(outcome.path)\n skipReasonCounts.set(outcome.reason, (skipReasonCounts.get(outcome.reason) ?? 0) + 1)\n }\n }\n\n if (result.skipped.length > 0) {\n console.warn(`GetMonitor: could not upload ${result.skipped.length} source map(s); continuing without them.`)\n for (const [reason, count] of skipReasonCounts) {\n console.warn(` - ${reason} (${count}x)`)\n }\n }\n\n return result\n}\n"],"names":["readdirSync","join","existsSync","readFileSync","dirname","execFileSync","randomUUID","relative","writeFileSync","rmSync"],"mappings":";;;;;;;AAAA;AASA,MAAM,kBAAkB,GAAG,0CAA0C;AAErE;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;AAE7C;;;;AAI2C;AACrC,SAAU,iBAAiB,CAAC,SAAiB,EAAA;IACjD,MAAM,SAAS,GAAe,EAAE;AAChC,IAAA,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC;AAC1B,IAAA,OAAO,SAAS;AAClB;AAEA,SAAS,IAAI,CAAC,GAAW,EAAE,SAAqB,EAAA;AAC9C,IAAA,KAAK,MAAM,KAAK,IAAIA,mBAAW,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,EAAE;QAC7D,MAAM,QAAQ,GAAGC,cAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC;AACtC,QAAA,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE;AACvB,YAAA,IAAI,CAAC,QAAQ,EAAE,SAAS,CAAC;QAC3B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
171
|
|
|
172
172
|
// packages/cli/src/uploadSourceMap.ts
|
|
173
173
|
/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */
|
|
174
|
-
const DEFAULT_API_HOST = 'https://
|
|
174
|
+
const DEFAULT_API_HOST = 'https://track.getmonitor.io';
|
|
175
175
|
/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.
|
|
176
176
|
* Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides
|
|
177
177
|
* what "failed" means for its own result reporting and disk-write ordering. */
|
|
@@ -196,7 +196,11 @@ async function uploadSourceMap(params) {
|
|
|
196
196
|
body: form,
|
|
197
197
|
});
|
|
198
198
|
if (!response.ok) {
|
|
199
|
-
|
|
199
|
+
// Deliberately excludes `params.filename` — a real deployment can have hundreds/thousands
|
|
200
|
+
// of artifacts fail identically (e.g. one bad auth token), and processSourceMaps
|
|
201
|
+
// deduplicates these messages to log the reason once instead of once per file. Baking the
|
|
202
|
+
// filename in here would make every message unique and defeat that dedup.
|
|
203
|
+
throw new Error(`${response.status} ${response.statusText}`);
|
|
200
204
|
}
|
|
201
205
|
}
|
|
202
206
|
|
|
@@ -220,24 +224,42 @@ async function processSourceMaps(options) {
|
|
|
220
224
|
}
|
|
221
225
|
const release = resolveRelease(options.directory, options.release);
|
|
222
226
|
const artifacts = discoverArtifacts(options.directory);
|
|
223
|
-
// Indexed by each artifact's position in `artifacts` rather than appended in completion
|
|
224
|
-
// order, so the final result below is deterministic no matter which worker finishes first.
|
|
225
227
|
const outcomes = new Array(artifacts.length);
|
|
226
228
|
const processOne = async (index) => {
|
|
227
229
|
const artifact = artifacts[index];
|
|
228
230
|
const debugId = randomUUID();
|
|
229
231
|
let injected;
|
|
232
|
+
// Local step: reading the artifact and injecting its debug ID. A failure here (unreadable
|
|
233
|
+
// file, malformed map JSON) means the build's own output is broken — that's a real bug
|
|
234
|
+
// worth failing CI over, so it's tracked in `failed` and logged per-file: with a genuine
|
|
235
|
+
// local bug there are normally only one or a handful of these, unlike a systemic upload
|
|
236
|
+
// outage below.
|
|
230
237
|
try {
|
|
231
238
|
const originalJs = readFileSync(artifact.jsPath, 'utf8');
|
|
232
239
|
const originalMap = readFileSync(artifact.mapPath, 'utf8');
|
|
233
240
|
// injectDebugId is a pure function that throws on malformed map JSON (by design — see
|
|
234
|
-
// its own doc comment).
|
|
235
|
-
//
|
|
236
|
-
//
|
|
237
|
-
//
|
|
238
|
-
//
|
|
239
|
-
//
|
|
241
|
+
// its own doc comment). One corrupt/unreadable artifact on disk must not abort
|
|
242
|
+
// processing of every other artifact in the directory, the same failure-isolation
|
|
243
|
+
// principle discoverArtifacts applies to unreadable files during its walk. Nothing has
|
|
244
|
+
// been uploaded or written yet at this point, so a thrown injectDebugId failure leaves
|
|
245
|
+
// the artifact's files completely untouched, and it's safe to report it as `failed` for
|
|
246
|
+
// a retry.
|
|
240
247
|
injected = injectDebugId(originalJs, originalMap, debugId);
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error);
|
|
251
|
+
outcomes[index] = { path: artifact.jsPath, kind: 'failed' };
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
// Remote step: uploading to the ingest API. Unlike the local step above, this artifact was
|
|
255
|
+
// perfectly fine — the *endpoint* rejected the request or was unreachable (bad/expired auth
|
|
256
|
+
// token, network outage, backend 5xx). That's an infra/connectivity problem outside this
|
|
257
|
+
// build's control, not a bug in it, so it's tracked separately in `skipped` (never `failed`)
|
|
258
|
+
// and deliberately NOT logged per-file here: an outage or bad token fails every one of
|
|
259
|
+
// potentially thousands of artifacts identically, and logging each one would drown out
|
|
260
|
+
// everything else in the build's output. The deduplicated reason is logged once, after all
|
|
261
|
+
// artifacts finish, by the summary block below.
|
|
262
|
+
try {
|
|
241
263
|
await uploadSourceMap({
|
|
242
264
|
apiHost: options.apiHost,
|
|
243
265
|
authToken,
|
|
@@ -251,27 +273,26 @@ async function processSourceMaps(options) {
|
|
|
251
273
|
});
|
|
252
274
|
}
|
|
253
275
|
catch (error) {
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
outcomes[index] = { path: artifact.jsPath, ok: false };
|
|
276
|
+
outcomes[index] = {
|
|
277
|
+
path: artifact.jsPath,
|
|
278
|
+
kind: 'skipped',
|
|
279
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
280
|
+
};
|
|
260
281
|
return;
|
|
261
282
|
}
|
|
262
283
|
try {
|
|
263
284
|
writeFileSync(artifact.jsPath, injected.js);
|
|
264
285
|
rmSync(artifact.mapPath);
|
|
265
|
-
outcomes[index] = { path: artifact.jsPath,
|
|
286
|
+
outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' };
|
|
266
287
|
}
|
|
267
288
|
catch (cleanupError) {
|
|
268
|
-
// The upload above already succeeded, so this must never land in `failed`
|
|
269
|
-
// retrying
|
|
289
|
+
// The upload above already succeeded, so this must never land in `failed` or `skipped` —
|
|
290
|
+
// a caller retrying either would mint a fresh debugId and re-upload, orphaning this
|
|
270
291
|
// upload server-side under the old one with no way to reconcile the two. The local
|
|
271
292
|
// cleanup failure (disk full, permission error, file lock) is real and worth knowing
|
|
272
293
|
// about, so it's surfaced here rather than silently swallowed, but it doesn't change
|
|
273
294
|
// the artifact's outcome.
|
|
274
|
-
outcomes[index] = { path: artifact.jsPath,
|
|
295
|
+
outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' };
|
|
275
296
|
console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError);
|
|
276
297
|
}
|
|
277
298
|
};
|
|
@@ -286,9 +307,25 @@ async function processSourceMaps(options) {
|
|
|
286
307
|
};
|
|
287
308
|
const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length);
|
|
288
309
|
await Promise.all(Array.from({ length: workerCount }, runWorker));
|
|
289
|
-
const result = { uploaded: [], failed: [] };
|
|
310
|
+
const result = { uploaded: [], failed: [], skipped: [] };
|
|
311
|
+
// Counts occurrences of each distinct skip reason, preserving first-seen order, so the
|
|
312
|
+
// summary below reads one line per *kind* of problem rather than one line per file.
|
|
313
|
+
const skipReasonCounts = new Map();
|
|
290
314
|
for (const outcome of outcomes) {
|
|
291
|
-
(outcome.
|
|
315
|
+
if (outcome.kind === 'uploaded')
|
|
316
|
+
result.uploaded.push(outcome.path);
|
|
317
|
+
else if (outcome.kind === 'failed')
|
|
318
|
+
result.failed.push(outcome.path);
|
|
319
|
+
else {
|
|
320
|
+
result.skipped.push(outcome.path);
|
|
321
|
+
skipReasonCounts.set(outcome.reason, (skipReasonCounts.get(outcome.reason) ?? 0) + 1);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (result.skipped.length > 0) {
|
|
325
|
+
console.warn(`GetMonitor: could not upload ${result.skipped.length} source map(s); continuing without them.`);
|
|
326
|
+
for (const [reason, count] of skipReasonCounts) {
|
|
327
|
+
console.warn(` - ${reason} (${count}x)`);
|
|
328
|
+
}
|
|
292
329
|
}
|
|
293
330
|
return result;
|
|
294
331
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/discoverArtifacts.ts","../src/injectDebugId.ts","../src/resolveRelease.ts","../src/uploadSourceMap.ts","../src/processSourceMaps.ts"],"sourcesContent":["// packages/cli/src/discoverArtifacts.ts\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Artifact {\n jsPath: string\n mapPath: string\n}\n\nconst SOURCE_MAPPING_URL = /^\\s*\\/\\/#\\s*sourceMappingURL=(\\S+)\\s*$/gm\n\n// Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit\n// ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's \"type\") — all three\n// show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e\n// test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real\n// `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and\n// unstripped even though `.output/` itself was already fully written by the time discovery ran.\nconst JS_EXTENSIONS = ['.js', '.mjs', '.cjs']\n\n/** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its\n * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the\n * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,\n * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no\n * resolvable map either way is skipped. */\nexport function discoverArtifacts(directory: string): Artifact[] {\n const artifacts: Artifact[] = []\n walk(directory, artifacts)\n return artifacts\n}\n\nfunction walk(dir: string, artifacts: Artifact[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n walk(fullPath, artifacts)\n } else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {\n const mapPath = resolveMapPath(fullPath)\n if (mapPath) artifacts.push({ jsPath: fullPath, mapPath })\n }\n }\n}\n\nfunction resolveMapPath(jsPath: string): string | undefined {\n const commentMapPath = readSourceMappingUrlComment(jsPath)\n if (commentMapPath && existsSync(commentMapPath)) return commentMapPath\n\n const fallbackMapPath = `${jsPath}.map`\n if (existsSync(fallbackMapPath)) return fallbackMapPath\n\n return undefined\n}\n\nfunction readSourceMappingUrlComment(jsPath: string): string | undefined {\n let content: string\n try {\n content = readFileSync(jsPath, 'utf8')\n } catch {\n // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it\n // like \"no comment found\" rather than aborting the whole discoverArtifacts() walk.\n return undefined\n }\n\n const matches = [...content.matchAll(SOURCE_MAPPING_URL)]\n if (matches.length === 0) return undefined\n\n // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat\n // concatenated/reprocessed output — later comments supersede earlier ones.\n const reference = matches.at(-1)![1]\n if (reference.startsWith('data:')) return undefined // embedded map, nothing to discover on disk\n\n return join(dirname(jsPath), reference)\n}\n","// packages/cli/src/injectDebugId.ts\n\nexport interface InjectedArtifact {\n js: string\n map: string\n}\n\n/** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in\n * memory — callers decide whether/when to persist the result to disk (processSourceMaps\n * only writes it after a successful upload, so a failed upload never leaves partially\n * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)\n * removed, since the source map it names is only ever kept in GetMonitor's backend after\n * a successful upload — never served publicly alongside it.\n *\n * `originalMapJson` must be valid JSON — this is a pure function with no fallback to\n * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's\n * caller expects a definite result), so a malformed map is left to throw via JSON.parse\n * rather than being swallowed here. */\nexport function injectDebugId(originalJs: string, originalMapJson: string, debugId: string): InjectedArtifact {\n const withoutMapComment = originalJs\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))\n .join('\\n')\n\n const map = JSON.parse(originalMapJson)\n map.debugId = debugId\n\n return {\n js: `${withoutMapComment}\\n${buildInjectedSnippet(debugId)}`,\n map: JSON.stringify(map),\n }\n}\n\n/** At load time, captures this statement's own `Error().stack`, extracts this file's\n * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for\n * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's\n * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,\n * it scans every stack line and takes the first one that matches any of those shapes, rather\n * than assuming a fixed line index — V8 prefixes an `\"ErrorType: message\"` header line that\n * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong\n * file's identity) on non-V8 engines; the header line simply fails to match any frame regex\n * and is skipped automatically. A later real error whose frame.filename is parsed from the\n * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any\n * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak\n * into the file's module scope.\n *\n * `debugId` is interpolated unescaped into the generated snippet's string literal. That's\n * safe today because every caller in this system sources `debugId` from\n * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but\n * this function itself doesn't enforce that shape, so a caller passing an arbitrary string\n * containing `'` or `\\` would produce invalid/injected JS here. Flagged, not fixed, since\n * validating/escaping isn't part of this function's specified contract. */\nfunction buildInjectedSnippet(debugId: string): string {\n return (\n \";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\\\n');var m=null;\" +\n 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +\n \"m=l.match(/\\\\((.*):(\\\\d+):(\\\\d+)\\\\)\\\\s*$/)||l.match(/at (.*):(\\\\d+):(\\\\d+)\\\\s*$/)||l.match(/@(.*):(\\\\d+):(\\\\d+)\\\\s*$/)}\" +\n \"var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);\" +\n `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +\n '}}catch(e){}})();'\n )\n}\n","// packages/cli/src/resolveRelease.ts\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit\n * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside\n * a git working tree) -> `version` field of the nearest package.json walking up from\n * `directory`. Matches the SDKs' own optional `release` field so events and source maps\n * for the same deploy carry the same value. */\nexport function resolveRelease(directory: string, explicit?: string): string {\n if (explicit) return explicit\n if (process.env.GETMONITOR_RELEASE) return process.env.GETMONITOR_RELEASE\n\n const gitSha = tryGitSha(directory)\n if (gitSha) return gitSha\n\n const packageVersion = tryPackageVersion(directory)\n if (packageVersion) return packageVersion\n\n throw new Error(\n 'Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a \"version\" field.',\n )\n}\n\nfunction tryGitSha(directory: string): string | undefined {\n try {\n return execFileSync('git', ['rev-parse', 'HEAD'], {\n cwd: directory,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim()\n } catch {\n return undefined\n }\n}\n\nfunction tryPackageVersion(directory: string): string | undefined {\n let dir = directory\n for (let i = 0; i < 20; i++) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n return typeof pkg.version === 'string' ? pkg.version : undefined\n } catch {\n return undefined\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n return undefined\n}\n","// packages/cli/src/uploadSourceMap.ts\n\n/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */\nexport const DEFAULT_API_HOST = 'https://ingest.getmonitor.io'\n\nexport interface UploadSourceMapParams {\n /**\n * @internal Test-only override for redirecting delivery to a local mock server (see\n * cli/e2e/processSourceMaps.spec.ts and the nextjs-config/nuxt e2e suites). Never exposed\n * through the public CLI/programmatic surface — real usage always ships to\n * {@link DEFAULT_API_HOST}.\n */\n apiHost?: string\n authToken: string\n release: string\n debugId: string\n filename: string\n mapContent: string\n fetchImpl?: typeof fetch\n}\n\n/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.\n * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides\n * what \"failed\" means for its own result reporting and disk-write ordering. */\nexport async function uploadSourceMap(params: UploadSourceMapParams): Promise<void> {\n // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native\n // fetch() throws \"Illegal invocation\" if called with a `this` other than\n // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below\n // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this\n // bind is defensive/consistent rather than load-bearing for this particular call site — but\n // keeping the same default expression as HttpTransport avoids a divergent default if this\n // code is ever refactored into a method.\n const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis)\n const apiHost = params.apiHost ?? DEFAULT_API_HOST\n\n const form = new FormData()\n form.set('release', params.release)\n form.set('debugId', params.debugId)\n form.set('filename', params.filename)\n form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`)\n\n const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${params.authToken}` },\n body: form,\n })\n\n if (!response.ok) {\n throw new Error(`Source map upload failed for ${params.filename}: ${response.status} ${response.statusText}`)\n }\n}\n","// packages/cli/src/processSourceMaps.ts\nimport { randomUUID } from 'node:crypto'\nimport { readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { relative } from 'node:path'\nimport { discoverArtifacts } from './discoverArtifacts'\nimport { injectDebugId, InjectedArtifact } from './injectDebugId'\nimport { resolveRelease } from './resolveRelease'\nimport { uploadSourceMap } from './uploadSourceMap'\nimport { ProcessSourceMapsOptions, ProcessSourceMapsResult } from './types'\n\n/**\n * @internal Test-only host override, intersected into `processSourceMaps`'s options but\n * deliberately not part of the exported `ProcessSourceMapsOptions` type — see\n * `uploadSourceMap`'s `UploadSourceMapParams.apiHost`. Used by this package's own e2e suite\n * and by nextjs-config/nuxt's e2e suites (via their own internal overrides) to redirect\n * delivery to a local mock server; real callers must never set it.\n */\ninterface InternalTestOverrides {\n apiHost?: string\n}\n\n/** Number of artifacts uploaded at once. Each upload is an independent network round trip to\n * ingester-api, so processing them one at a time made wall-clock time scale linearly with\n * artifact count for no reason — a real Next.js build can emit well over a thousand of them,\n * turning a few hundred ms of per-file latency into many minutes of serial waiting. */\nconst UPLOAD_CONCURRENCY = 20\n\n/** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a\n * debug ID, uploads the tagged source map, and — only on a successful upload — writes the\n * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload\n * fails is left completely untouched on disk, so it can be retried by re-running this\n * function against the same directory. Artifacts are uploaded concurrently (bounded by\n * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match\n * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */\nexport async function processSourceMaps(\n options: ProcessSourceMapsOptions & InternalTestOverrides\n): Promise<ProcessSourceMapsResult> {\n const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN\n if (!authToken) {\n throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.')\n }\n\n const release = resolveRelease(options.directory, options.release)\n const artifacts = discoverArtifacts(options.directory)\n // Indexed by each artifact's position in `artifacts` rather than appended in completion\n // order, so the final result below is deterministic no matter which worker finishes first.\n const outcomes: Array<{ path: string; ok: boolean }> = new Array(artifacts.length)\n\n const processOne = async (index: number): Promise<void> => {\n const artifact = artifacts[index]\n const debugId = randomUUID()\n let injected: InjectedArtifact\n\n try {\n const originalJs = readFileSync(artifact.jsPath, 'utf8')\n const originalMap = readFileSync(artifact.mapPath, 'utf8')\n // injectDebugId is a pure function that throws on malformed map JSON (by design — see\n // its own doc comment). That's deliberately caught here, alongside upload failures: one\n // corrupt/unreadable artifact on disk must not abort processing of every other artifact\n // in the directory, the same failure-isolation principle discoverArtifacts applies to\n // unreadable files during its walk. Nothing has been uploaded or written yet at this\n // point, so a thrown injectDebugId or upload failure leaves the artifact's files\n // completely untouched, and it's safe to report it as `failed` for a retry.\n injected = injectDebugId(originalJs, originalMap, debugId)\n\n await uploadSourceMap({\n apiHost: options.apiHost,\n authToken,\n release,\n debugId,\n // Relative to options.directory, not the absolute on-disk path — the backend has no\n // use for (and shouldn't see) the build machine's local filesystem layout.\n filename: relative(options.directory, artifact.jsPath),\n mapContent: injected.map,\n fetchImpl: options.fetchImpl,\n })\n } catch (error) {\n // Surfaced here rather than swallowed: this is the only place the actual failure reason\n // (injectDebugId's malformed-JSON error, or uploadSourceMap's `status statusText` message)\n // is available. Without logging it, callers only ever see a bare list of failed paths with\n // no way to tell an auth failure from a malformed map from a network error.\n console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error)\n outcomes[index] = { path: artifact.jsPath, ok: false }\n return\n }\n\n try {\n writeFileSync(artifact.jsPath, injected.js)\n rmSync(artifact.mapPath)\n outcomes[index] = { path: artifact.jsPath, ok: true }\n } catch (cleanupError) {\n // The upload above already succeeded, so this must never land in `failed` — a caller\n // retrying failed artifacts would mint a fresh debugId and re-upload, orphaning this\n // upload server-side under the old one with no way to reconcile the two. The local\n // cleanup failure (disk full, permission error, file lock) is real and worth knowing\n // about, so it's surfaced here rather than silently swallowed, but it doesn't change\n // the artifact's outcome.\n outcomes[index] = { path: artifact.jsPath, ok: true }\n console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError)\n }\n }\n\n // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared\n // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.\n let nextIndex = 0\n const runWorker = async (): Promise<void> => {\n while (nextIndex < artifacts.length) {\n const index = nextIndex++\n await processOne(index)\n }\n }\n const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length)\n await Promise.all(Array.from({ length: workerCount }, runWorker))\n\n const result: ProcessSourceMapsResult = { uploaded: [], failed: [] }\n for (const outcome of outcomes) {\n ;(outcome.ok ? result.uploaded : result.failed).push(outcome.path)\n }\n return result\n}\n"],"names":[],"mappings":";;;;;AAAA;AASA,MAAM,kBAAkB,GAAG,0CAA0C;AAErE;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;AAE7C;;;;AAI2C;AACrC,SAAU,iBAAiB,CAAC,SAAiB,EAAA;IACjD,MAAM,SAAS,GAAe,EAAE;AAChC,IAAA,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC;AAC1B,IAAA,OAAO,SAAS;AAClB;AAEA,SAAS,IAAI,CAAC,GAAW,EAAE,SAAqB,EAAA;AAC9C,IAAA,KAAK,MAAM,KAAK,IAAI,WAAW,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,EAAE;QAC7D,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC;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AE,EAAE;AACpE,IAAA,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;QAC7B,CAAC,OAAO,CAAC,EAAE,GAAG,MAAM,CAAC,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IACpE;AACA,IAAA,OAAO,MAAM;AACf;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/discoverArtifacts.ts","../src/injectDebugId.ts","../src/resolveRelease.ts","../src/uploadSourceMap.ts","../src/processSourceMaps.ts"],"sourcesContent":["// packages/cli/src/discoverArtifacts.ts\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Artifact {\n jsPath: string\n mapPath: string\n}\n\nconst SOURCE_MAPPING_URL = /^\\s*\\/\\/#\\s*sourceMappingURL=(\\S+)\\s*$/gm\n\n// Node recognizes three JS module extensions with runtime meaning (`.js`, `.mjs` for explicit\n// ESM, `.cjs` for explicit CommonJS regardless of the nearest package.json's \"type\") — all three\n// show up as real build output. Nitro's node-server preset (used by `@getmonitor/nuxt`'s e2e\n// test), for one, emits `.output/server/**/*.mjs` unconditionally: verified against a real\n// `nuxt build`, where a `.js`-only match left every server chunk's `.map` file undiscovered and\n// unstripped even though `.output/` itself was already fully written by the time discovery ran.\nconst JS_EXTENSIONS = ['.js', '.mjs', '.cjs']\n\n/** Recursively finds every JS file (`.js`, `.mjs`, `.cjs`) under `directory` and resolves its\n * source map path primarily via its `//# sourceMappingURL=` comment (resolved relative to the\n * JS file's own directory), falling back to same-basename-plus-`.map` when there's no comment,\n * the comment references a data: URI, or the referenced file doesn't exist. A JS file with no\n * resolvable map either way is skipped. */\nexport function discoverArtifacts(directory: string): Artifact[] {\n const artifacts: Artifact[] = []\n walk(directory, artifacts)\n return artifacts\n}\n\nfunction walk(dir: string, artifacts: Artifact[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n walk(fullPath, artifacts)\n } else if (entry.isFile() && JS_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {\n const mapPath = resolveMapPath(fullPath)\n if (mapPath) artifacts.push({ jsPath: fullPath, mapPath })\n }\n }\n}\n\nfunction resolveMapPath(jsPath: string): string | undefined {\n const commentMapPath = readSourceMappingUrlComment(jsPath)\n if (commentMapPath && existsSync(commentMapPath)) return commentMapPath\n\n const fallbackMapPath = `${jsPath}.map`\n if (existsSync(fallbackMapPath)) return fallbackMapPath\n\n return undefined\n}\n\nfunction readSourceMappingUrlComment(jsPath: string): string | undefined {\n let content: string\n try {\n content = readFileSync(jsPath, 'utf8')\n } catch {\n // Unreadable file (permission denied, broken symlink, deleted mid-walk, etc.) — treat it\n // like \"no comment found\" rather than aborting the whole discoverArtifacts() walk.\n return undefined\n }\n\n const matches = [...content.matchAll(SOURCE_MAPPING_URL)]\n if (matches.length === 0) return undefined\n\n // The LAST sourceMappingURL comment in the file wins, matching how bundlers/browsers treat\n // concatenated/reprocessed output — later comments supersede earlier ones.\n const reference = matches.at(-1)![1]\n if (reference.startsWith('data:')) return undefined // embedded map, nothing to discover on disk\n\n return join(dirname(jsPath), reference)\n}\n","// packages/cli/src/injectDebugId.ts\n\nexport interface InjectedArtifact {\n js: string\n map: string\n}\n\n/** Computes the debug-ID-injected JS content and the debug-ID-tagged source map JSON, in\n * memory — callers decide whether/when to persist the result to disk (processSourceMaps\n * only writes it after a successful upload, so a failed upload never leaves partially\n * mutated files behind). The injected JS also has its `//# sourceMappingURL=` comment(s)\n * removed, since the source map it names is only ever kept in GetMonitor's backend after\n * a successful upload — never served publicly alongside it.\n *\n * `originalMapJson` must be valid JSON — this is a pure function with no fallback to\n * degrade to (unlike discoverArtifacts, which can skip an unreadable file, this function's\n * caller expects a definite result), so a malformed map is left to throw via JSON.parse\n * rather than being swallowed here. */\nexport function injectDebugId(originalJs: string, originalMapJson: string, debugId: string): InjectedArtifact {\n const withoutMapComment = originalJs\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('//# sourceMappingURL='))\n .join('\\n')\n\n const map = JSON.parse(originalMapJson)\n map.debugId = debugId\n\n return {\n js: `${withoutMapComment}\\n${buildInjectedSnippet(debugId)}`,\n map: JSON.stringify(map),\n }\n}\n\n/** At load time, captures this statement's own `Error().stack`, extracts this file's\n * identity from it using the same frame-shape @getmonitor/core's parseStackTrace parses for\n * real errors (V8's `at ... (file:line:col)`, V8's bare `at file:line:col`, and Gecko's\n * `fn@file:line:col`), and registers the debug ID under that identity. Like parseStackTrace,\n * it scans every stack line and takes the first one that matches any of those shapes, rather\n * than assuming a fixed line index — V8 prefixes an `\"ErrorType: message\"` header line that\n * Gecko and Safari don't emit, so a fixed index would grab the wrong frame (or the wrong\n * file's identity) on non-V8 engines; the header line simply fails to match any frame regex\n * and is skipped automatically. A later real error whose frame.filename is parsed from the\n * same JS-engine stack serialization will look up the same key. Wrapped in try/catch so any\n * parsing edge case can never break the host app; wrapped in an IIFE so its locals don't leak\n * into the file's module scope.\n *\n * `debugId` is interpolated unescaped into the generated snippet's string literal. That's\n * safe today because every caller in this system sources `debugId` from\n * `crypto.randomUUID()` (a later task), which can never contain a quote or backslash — but\n * this function itself doesn't enforce that shape, so a caller passing an arbitrary string\n * containing `'` or `\\` would produce invalid/injected JS here. Flagged, not fixed, since\n * validating/escaping isn't part of this function's specified contract. */\nfunction buildInjectedSnippet(debugId: string): string {\n return (\n \";(function(){try{var s=(new Error()).stack||'';var ls=s.split('\\\\n');var m=null;\" +\n 'for(var i=0;i<ls.length&&!m;i++){var l=ls[i];' +\n \"m=l.match(/\\\\((.*):(\\\\d+):(\\\\d+)\\\\)\\\\s*$/)||l.match(/at (.*):(\\\\d+):(\\\\d+)\\\\s*$/)||l.match(/@(.*):(\\\\d+):(\\\\d+)\\\\s*$/)}\" +\n \"var f=m&&m[1];if(f){var g=(typeof globalThis!=='undefined'?globalThis:self);\" +\n `g.__getmonitorDebugIds=g.__getmonitorDebugIds||{};g.__getmonitorDebugIds[f]='${debugId}';` +\n '}}catch(e){}})();'\n )\n}\n","// packages/cli/src/resolveRelease.ts\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/** Resolves the release identifier to tag uploaded source maps with. Precedence: explicit\n * argument -> GETMONITOR_RELEASE env var -> current git commit SHA (if `directory` is inside\n * a git working tree) -> `version` field of the nearest package.json walking up from\n * `directory`. Matches the SDKs' own optional `release` field so events and source maps\n * for the same deploy carry the same value. */\nexport function resolveRelease(directory: string, explicit?: string): string {\n if (explicit) return explicit\n if (process.env.GETMONITOR_RELEASE) return process.env.GETMONITOR_RELEASE\n\n const gitSha = tryGitSha(directory)\n if (gitSha) return gitSha\n\n const packageVersion = tryPackageVersion(directory)\n if (packageVersion) return packageVersion\n\n throw new Error(\n 'Could not resolve a release. Pass --release, set GETMONITOR_RELEASE, run inside a git repository, or add a package.json with a \"version\" field.',\n )\n}\n\nfunction tryGitSha(directory: string): string | undefined {\n try {\n return execFileSync('git', ['rev-parse', 'HEAD'], {\n cwd: directory,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim()\n } catch {\n return undefined\n }\n}\n\nfunction tryPackageVersion(directory: string): string | undefined {\n let dir = directory\n for (let i = 0; i < 20; i++) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n return typeof pkg.version === 'string' ? pkg.version : undefined\n } catch {\n return undefined\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n return undefined\n}\n","// packages/cli/src/uploadSourceMap.ts\n\n/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */\nexport const DEFAULT_API_HOST = 'https://track.getmonitor.io'\n\nexport interface UploadSourceMapParams {\n /**\n * @internal Test-only override for redirecting delivery to a local mock server (see\n * cli/e2e/processSourceMaps.spec.ts and the nextjs-config/nuxt e2e suites). Never exposed\n * through the public CLI/programmatic surface — real usage always ships to\n * {@link DEFAULT_API_HOST}.\n */\n apiHost?: string\n authToken: string\n release: string\n debugId: string\n filename: string\n mapContent: string\n fetchImpl?: typeof fetch\n}\n\n/** POSTs a single source map artifact to ingester-api's `/api/v1/sourcemaps` contract.\n * Throws on any non-2xx response or network failure — the caller (processSourceMaps) decides\n * what \"failed\" means for its own result reporting and disk-write ordering. */\nexport async function uploadSourceMap(params: UploadSourceMapParams): Promise<void> {\n // Must bind to globalThis, mirroring @getmonitor/core's HttpTransport: browsers' native\n // fetch() throws \"Illegal invocation\" if called with a `this` other than\n // Window/WorkerGlobalScope. Here fetchImpl is invoked as a plain function call below\n // (`fetchImpl(url, init)`, never `params.fetchImpl(...)` or `this.fetchImpl(...)`), so this\n // bind is defensive/consistent rather than load-bearing for this particular call site — but\n // keeping the same default expression as HttpTransport avoids a divergent default if this\n // code is ever refactored into a method.\n const fetchImpl = params.fetchImpl ?? fetch.bind(globalThis)\n const apiHost = params.apiHost ?? DEFAULT_API_HOST\n\n const form = new FormData()\n form.set('release', params.release)\n form.set('debugId', params.debugId)\n form.set('filename', params.filename)\n form.set('sourcemap', new Blob([params.mapContent], { type: 'application/json' }), `${params.filename}.map`)\n\n const response = await fetchImpl(`${apiHost}/api/v1/sourcemaps`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${params.authToken}` },\n body: form,\n })\n\n if (!response.ok) {\n // Deliberately excludes `params.filename` — a real deployment can have hundreds/thousands\n // of artifacts fail identically (e.g. one bad auth token), and processSourceMaps\n // deduplicates these messages to log the reason once instead of once per file. Baking the\n // filename in here would make every message unique and defeat that dedup.\n throw new Error(`${response.status} ${response.statusText}`)\n }\n}\n","// packages/cli/src/processSourceMaps.ts\nimport { randomUUID } from 'node:crypto'\nimport { readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { relative } from 'node:path'\nimport { discoverArtifacts } from './discoverArtifacts'\nimport { injectDebugId, InjectedArtifact } from './injectDebugId'\nimport { resolveRelease } from './resolveRelease'\nimport { uploadSourceMap } from './uploadSourceMap'\nimport { ProcessSourceMapsOptions, ProcessSourceMapsResult } from './types'\n\n/**\n * @internal Test-only host override, intersected into `processSourceMaps`'s options but\n * deliberately not part of the exported `ProcessSourceMapsOptions` type — see\n * `uploadSourceMap`'s `UploadSourceMapParams.apiHost`. Used by this package's own e2e suite\n * and by nextjs-config/nuxt's e2e suites (via their own internal overrides) to redirect\n * delivery to a local mock server; real callers must never set it.\n */\ninterface InternalTestOverrides {\n apiHost?: string\n}\n\n/** Number of artifacts uploaded at once. Each upload is an independent network round trip to\n * ingester-api, so processing them one at a time made wall-clock time scale linearly with\n * artifact count for no reason — a real Next.js build can emit well over a thousand of them,\n * turning a few hundred ms of per-file latency into many minutes of serial waiting. */\nconst UPLOAD_CONCURRENCY = 20\n\n/** Finds every JS/map artifact pair under `options.directory`, and for each one: injects a\n * debug ID, uploads the tagged source map, and — only on a successful upload — writes the\n * debug-ID-injected JS back to disk and deletes the `.map` file. An artifact whose upload\n * fails is left completely untouched on disk, so it can be retried by re-running this\n * function against the same directory. Artifacts are uploaded concurrently (bounded by\n * `UPLOAD_CONCURRENCY`), but `result.uploaded`/`result.failed` are always ordered to match\n * `discoverArtifacts`'s output, regardless of which upload happens to finish first. */\nexport async function processSourceMaps(\n options: ProcessSourceMapsOptions & InternalTestOverrides\n): Promise<ProcessSourceMapsResult> {\n const authToken = options.authToken ?? process.env.GETMONITOR_AUTH_TOKEN\n if (!authToken) {\n throw new Error('Missing auth token. Pass --auth-token or set GETMONITOR_AUTH_TOKEN.')\n }\n\n const release = resolveRelease(options.directory, options.release)\n const artifacts = discoverArtifacts(options.directory)\n // Indexed by each artifact's position in `artifacts` rather than appended in completion\n // order, so the final result below is deterministic no matter which worker finishes first.\n type Outcome =\n | { path: string; kind: 'uploaded' }\n | { path: string; kind: 'failed' }\n | { path: string; kind: 'skipped'; reason: string }\n const outcomes: Outcome[] = new Array(artifacts.length)\n\n const processOne = async (index: number): Promise<void> => {\n const artifact = artifacts[index]\n const debugId = randomUUID()\n let injected: InjectedArtifact\n\n // Local step: reading the artifact and injecting its debug ID. A failure here (unreadable\n // file, malformed map JSON) means the build's own output is broken — that's a real bug\n // worth failing CI over, so it's tracked in `failed` and logged per-file: with a genuine\n // local bug there are normally only one or a handful of these, unlike a systemic upload\n // outage below.\n try {\n const originalJs = readFileSync(artifact.jsPath, 'utf8')\n const originalMap = readFileSync(artifact.mapPath, 'utf8')\n // injectDebugId is a pure function that throws on malformed map JSON (by design — see\n // its own doc comment). One corrupt/unreadable artifact on disk must not abort\n // processing of every other artifact in the directory, the same failure-isolation\n // principle discoverArtifacts applies to unreadable files during its walk. Nothing has\n // been uploaded or written yet at this point, so a thrown injectDebugId failure leaves\n // the artifact's files completely untouched, and it's safe to report it as `failed` for\n // a retry.\n injected = injectDebugId(originalJs, originalMap, debugId)\n } catch (error) {\n console.error(`Failed to process ${artifact.jsPath}:`, error instanceof Error ? error.message : error)\n outcomes[index] = { path: artifact.jsPath, kind: 'failed' }\n return\n }\n\n // Remote step: uploading to the ingest API. Unlike the local step above, this artifact was\n // perfectly fine — the *endpoint* rejected the request or was unreachable (bad/expired auth\n // token, network outage, backend 5xx). That's an infra/connectivity problem outside this\n // build's control, not a bug in it, so it's tracked separately in `skipped` (never `failed`)\n // and deliberately NOT logged per-file here: an outage or bad token fails every one of\n // potentially thousands of artifacts identically, and logging each one would drown out\n // everything else in the build's output. The deduplicated reason is logged once, after all\n // artifacts finish, by the summary block below.\n try {\n await uploadSourceMap({\n apiHost: options.apiHost,\n authToken,\n release,\n debugId,\n // Relative to options.directory, not the absolute on-disk path — the backend has no\n // use for (and shouldn't see) the build machine's local filesystem layout.\n filename: relative(options.directory, artifact.jsPath),\n mapContent: injected.map,\n fetchImpl: options.fetchImpl,\n })\n } catch (error) {\n outcomes[index] = {\n path: artifact.jsPath,\n kind: 'skipped',\n reason: error instanceof Error ? error.message : String(error),\n }\n return\n }\n\n try {\n writeFileSync(artifact.jsPath, injected.js)\n rmSync(artifact.mapPath)\n outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' }\n } catch (cleanupError) {\n // The upload above already succeeded, so this must never land in `failed` or `skipped` —\n // a caller retrying either would mint a fresh debugId and re-upload, orphaning this\n // upload server-side under the old one with no way to reconcile the two. The local\n // cleanup failure (disk full, permission error, file lock) is real and worth knowing\n // about, so it's surfaced here rather than silently swallowed, but it doesn't change\n // the artifact's outcome.\n outcomes[index] = { path: artifact.jsPath, kind: 'uploaded' }\n console.error(`Uploaded ${artifact.jsPath} but failed to update local files:`, cleanupError)\n }\n }\n\n // A fixed-size pool of workers, each pulling the next unclaimed artifact index off a shared\n // cursor, bounds concurrency to UPLOAD_CONCURRENCY regardless of how many artifacts there are.\n let nextIndex = 0\n const runWorker = async (): Promise<void> => {\n while (nextIndex < artifacts.length) {\n const index = nextIndex++\n await processOne(index)\n }\n }\n const workerCount = Math.min(UPLOAD_CONCURRENCY, artifacts.length)\n await Promise.all(Array.from({ length: workerCount }, runWorker))\n\n const result: ProcessSourceMapsResult = { uploaded: [], failed: [], skipped: [] }\n // Counts occurrences of each distinct skip reason, preserving first-seen order, so the\n // summary below reads one line per *kind* of problem rather than one line per file.\n const skipReasonCounts = new Map<string, number>()\n for (const outcome of outcomes) {\n if (outcome.kind === 'uploaded') result.uploaded.push(outcome.path)\n else if (outcome.kind === 'failed') result.failed.push(outcome.path)\n else {\n result.skipped.push(outcome.path)\n skipReasonCounts.set(outcome.reason, (skipReasonCounts.get(outcome.reason) ?? 0) + 1)\n }\n }\n\n if (result.skipped.length > 0) {\n console.warn(`GetMonitor: could not upload ${result.skipped.length} source map(s); continuing without them.`)\n for (const [reason, count] of skipReasonCounts) {\n console.warn(` - ${reason} (${count}x)`)\n }\n }\n\n return result\n}\n"],"names":[],"mappings":";;;;;AAAA;AASA,MAAM,kBAAkB,GAAG,0CAA0C;AAErE;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,KAAK,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,CAAC,IAAI,CAAC,CAAC;QACvF;IACF;IAEA,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;QAC7B,OAAO,CAAC,IAAI,CAAC,CAAA,6BAAA,EAAgC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAA,wCAAA,CAA0C,CAAC;QAC7G,KAAK,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,gBAAgB,EAAE;YAC9C,OAAO,CAAC,IAAI,CAAC,CAAA,IAAA,EAAO,MAAM,CAAA,EAAA,EAAK,KAAK,CAAA,EAAA,CAAI,CAAC;QAC3C;IACF;AAEA,IAAA,OAAO,MAAM;AACf;;;;"}
|
package/dist/types.d.ts
CHANGED
|
@@ -6,5 +6,11 @@ export interface ProcessSourceMapsOptions {
|
|
|
6
6
|
}
|
|
7
7
|
export interface ProcessSourceMapsResult {
|
|
8
8
|
uploaded: string[];
|
|
9
|
+
/** Artifacts whose local files (JS/map) were corrupt or unreadable — a real bug in this
|
|
10
|
+
* build's output, worth failing CI over. Never includes remote/upload failures; see `skipped`. */
|
|
9
11
|
failed: string[];
|
|
12
|
+
/** Artifacts whose upload to the ingest API failed — auth, connection, timeout, or a 5xx
|
|
13
|
+
* response. Deliberately kept separate from `failed`: these are infra/connectivity problems
|
|
14
|
+
* outside this build's control, not a bug in it, so callers must not fail the build over them. */
|
|
15
|
+
skipped: string[];
|
|
10
16
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** The one sourcemap-upload host every CLI invocation talks to — not customer-configurable. */
|
|
2
|
-
export declare const DEFAULT_API_HOST = "https://
|
|
2
|
+
export declare const DEFAULT_API_HOST = "https://track.getmonitor.io";
|
|
3
3
|
export interface UploadSourceMapParams {
|
|
4
4
|
/**
|
|
5
5
|
* @internal Test-only override for redirecting delivery to a local mock server (see
|