@autter/runtime-cli 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { A as AutterSourceMapsOptions, B as BUNDLE_RE, a as BuildOutputResult, b as BundleWithMap, D as DEFAULT_ENDPOINT, F as FatalUploadError, I as InjectOptions, c as InjectResult, M as MAX_MAP_CHARS, d as MAX_UPLOAD_BYTES, S as SNIPPET_LINE_KEY, U as UploadItem, e as UploadOptions, f as UploadSummary, g as findBundles, h as formatUploadSummary, i as injectBundle, j as injectDir, m as mapPathFor, p as processBuildOutput, r as readSourceMappingUrl, k as resolveEndpoint, s as servedFilename, l as shiftMappings, n as snippetLine, o as storedMapJson, q as stripSourceMappingUrl, u as uploadDir } from './build-CPXR9Xd3.js';
1
+ export { A as AutterSourceMapsOptions, B as BUNDLE_RE, a as BuildOutputResult, b as BundleWithMap, C as CLIENT_KEY_PREFIX, D as DEFAULT_ENDPOINT, F as FatalUploadError, I as InjectOptions, c as InjectResult, K as KEY_ADVICE, M as MAX_MAP_CHARS, d as MAX_UPLOAD_BYTES, S as SERVER_KEY_PREFIX, e as SNIPPET_LINE_KEY, U as UPLOAD_KEY_PREFIX, f as UploadItem, g as UploadOptions, h as UploadSummary, i as findBundles, j as formatUploadSummary, k as injectBundle, l as injectDir, m as isInAppSource, n as mapPathFor, p as processBuildOutput, r as readSourceMappingUrl, o as resolveEndpoint, s as servedFilename, q as serverUrlPrefix, t as shiftMappings, u as snippetLine, v as storedMapJson, w as storedSourcesContent, x as stripSourceMappingUrl, y as uploadDir } from './build-DGeoDkTh.js';
2
2
 
3
3
  /** 8-4-4-4-12 hex: the debug id shape shared with Rollup, Turbopack, esbuild
4
4
  * and Sentry tooling, and what the ingester accepts. */
@@ -14,13 +14,16 @@ declare function debugIdFor(bytes: Uint8Array | string): string;
14
14
  /** The id in the bundle's last `//# debugId=` comment, if any (ours, or one
15
15
  * a bundler wrote natively). */
16
16
  declare function readDebugIdComment(code: string): string | null;
17
- /** Property the browser SDK reads: `globalThis._autterDebugIds[stack] = id`. */
17
+ /** Property the SDKs read: `globalThis._autterDebugIds[stack] = id` (the
18
+ * browser SDK, and the Node and edge SDKs' `autter.debug_ids`, RF-05). */
18
19
  declare const DEBUG_ID_REGISTRY = "_autterDebugIds";
19
20
  /**
20
21
  * One line of ES5 that records this bundle's id under the stack of an Error
21
22
  * created inside it — the stack's first frame names the script URL the
22
- * browser actually loaded, which the SDK maps back to the id. `g.Error` keeps
23
- * working when the bundle shadows `Error` at top level. Never throws.
23
+ * browser loaded, or the file Node or an edge runtime ran, which the SDK
24
+ * maps back to the id. `g.Error` keeps working when the bundle shadows
25
+ * `Error` at top level. Never throws. The same snippet goes into browser
26
+ * and server bundles.
24
27
  */
25
28
  declare function debugIdSnippet(id: string): string;
26
29
  /** Whether the bundle already carries our registration snippet. (The
@@ -28,6 +31,66 @@ declare function debugIdSnippet(id: string): string;
28
31
  * contains it too.) */
29
32
  declare function hasDebugIdSnippet(code: string): boolean;
30
33
 
34
+ interface VerifyOptions {
35
+ /** Ingester base URL (default as for upload). */
36
+ endpoint?: string;
37
+ /** Default: $AUTTER_RUNTIME_KEY. */
38
+ key?: string;
39
+ /** Sent with the check (a debug id check ignores it). */
40
+ release?: string;
41
+ urlPrefix?: string;
42
+ /** Globs (relative to the directory) of JS files that are not bundles. */
43
+ ignore?: string[];
44
+ /** Report leftover .map files without failing (a step that runs before they are removed). */
45
+ allowMaps?: boolean;
46
+ /** A server bundle directory (tsup, esbuild, webpack or Next server
47
+ * output): leftover maps are reported, not failures — browsers never load
48
+ * them, and Node's own `--enable-source-maps` may use them. */
49
+ server?: boolean;
50
+ env?: NodeJS.ProcessEnv;
51
+ cwd?: string;
52
+ fetch?: typeof fetch;
53
+ }
54
+ interface VerifyBundle {
55
+ /** Relative to the directory. */
56
+ path: string;
57
+ status: "ok" | "failed" | "skipped";
58
+ debugId: string | null;
59
+ /** Why it failed, or why it was skipped. */
60
+ reasons: string[];
61
+ /** Whether the ingester has a map for its debug id (null: not checked). */
62
+ uploaded: boolean | null;
63
+ }
64
+ interface VerifyResult {
65
+ dir: string;
66
+ ok: boolean;
67
+ bundles: VerifyBundle[];
68
+ /** `.map` files in the directory (deploy risks unless allowMaps or server). */
69
+ maps: string[];
70
+ /** True when checked as server output (`--server`). */
71
+ server?: boolean;
72
+ upload: {
73
+ /** verified: every checked bundle's map is on the ingester; missing: some are not;
74
+ * unverified: not checked (no key, or an ingester that can't answer); error: the check failed. */
75
+ status: "verified" | "missing" | "unverified" | "error";
76
+ endpoint: string | null;
77
+ reason: string | null;
78
+ checked: number;
79
+ missing: number;
80
+ };
81
+ /** Every failure, one per file and reason. */
82
+ failures: Array<{
83
+ path: string;
84
+ reason: string;
85
+ }>;
86
+ }
87
+ /** A tiny glob: `**` any path, `*` any name part, `?` one character. A
88
+ * pattern without "/" matches the file name anywhere. */
89
+ declare function globToRegExp(glob: string): RegExp;
90
+ declare function verifyDir(dir: string, options?: VerifyOptions): Promise<VerifyResult>;
91
+ /** Human-readable report. */
92
+ declare function formatVerify(result: VerifyResult): string[];
93
+
31
94
  /**
32
95
  * Function scopes for scope-based frame names (like Sentry's
33
96
  * js-source-scopes and PostHog cymbal's `token.scope()`).
@@ -102,4 +165,4 @@ declare function gitHead(cwd?: string): string | null;
102
165
  */
103
166
  declare function resolveRelease(explicit?: string | null, env?: NodeJS.ProcessEnv, cwd?: string): ResolvedRelease;
104
167
 
105
- export { DEBUG_ID_RE, DEBUG_ID_REGISTRY, RELEASE_ENV_VARS, RELEASE_RE, type ResolvedRelease, SCOPES_KEY, SCOPES_VERSION, type ScopesResult, type SourceMapScopes, computeScopes, debugIdFor, debugIdSnippet, gitHead, hasDebugIdSnippet, normalizeDebugId, readDebugIdComment, resolveRelease };
168
+ export { DEBUG_ID_RE, DEBUG_ID_REGISTRY, RELEASE_ENV_VARS, RELEASE_RE, type ResolvedRelease, SCOPES_KEY, SCOPES_VERSION, type ScopesResult, type SourceMapScopes, type VerifyBundle, type VerifyOptions, type VerifyResult, computeScopes, debugIdFor, debugIdSnippet, formatVerify, gitHead, globToRegExp, hasDebugIdSnippet, normalizeDebugId, readDebugIdComment, resolveRelease, verifyDir };
package/dist/index.js CHANGED
@@ -1,16 +1,20 @@
1
1
  import {
2
2
  BUNDLE_RE,
3
+ CLIENT_KEY_PREFIX,
3
4
  DEBUG_ID_RE,
4
5
  DEBUG_ID_REGISTRY,
5
6
  DEFAULT_ENDPOINT,
6
7
  FatalUploadError,
8
+ KEY_ADVICE,
7
9
  MAX_MAP_CHARS,
8
10
  MAX_UPLOAD_BYTES,
9
11
  RELEASE_ENV_VARS,
10
12
  RELEASE_RE,
11
13
  SCOPES_KEY,
12
14
  SCOPES_VERSION,
15
+ SERVER_KEY_PREFIX,
13
16
  SNIPPET_LINE_KEY,
17
+ UPLOAD_KEY_PREFIX,
14
18
  computeScopes,
15
19
  debugIdFor,
16
20
  debugIdSnippet,
@@ -20,6 +24,7 @@ import {
20
24
  hasDebugIdSnippet,
21
25
  injectBundle,
22
26
  injectDir,
27
+ isInAppSource,
23
28
  mapPathFor,
24
29
  normalizeDebugId,
25
30
  processBuildOutput,
@@ -28,34 +33,291 @@ import {
28
33
  resolveEndpoint,
29
34
  resolveRelease,
30
35
  servedFilename,
36
+ serverUrlPrefix,
31
37
  shiftMappings,
32
38
  snippetLine,
33
39
  storedMapJson,
40
+ storedSourcesContent,
34
41
  stripSourceMappingUrl,
35
42
  uploadDir
36
- } from "./chunk-DQLLM2NT.js";
43
+ } from "./chunk-Q23FB5X3.js";
44
+
45
+ // src/verify.ts
46
+ import { existsSync } from "fs";
47
+ import { readdir, readFile } from "fs/promises";
48
+ import { dirname, join, relative, resolve, sep } from "path";
49
+ var CHECK_BATCH = 500;
50
+ var SNIPPET_ID_RE = /\(g\._autterDebugIds=g\._autterDebugIds\|\|\{\}\)\[s\]="([0-9a-f-]{36})"/;
51
+ var NOT_BUNDLES = [
52
+ [/(^|\/)_(build|ssg|middleware|clientMiddleware)Manifest\.js$/, "Next.js build manifest"],
53
+ // .next/server: middleware-build-manifest.js, next-font-manifest.js,
54
+ // server-reference-manifest.js, page_client-reference-manifest.js, …
55
+ [/(^|\/)[\w.-]*[-_]manifest\.js$/, "Next.js server manifest"],
56
+ [/(^|\/)chunks\/polyfills-[\w-]+\.js$/, "Next.js polyfills, copied prebuilt without a source map"],
57
+ [/(^|\/)(sw|service-worker|serviceWorker|firebase-messaging-sw|mockServiceWorker)\.js$/, "service worker (the browser SDK doesn't run there)"],
58
+ [/(^|\/)workbox-[\w-]+\.js$/, "service worker runtime (the browser SDK doesn't run there)"]
59
+ ];
60
+ function globToRegExp(glob) {
61
+ let re = "";
62
+ for (let i = 0; i < glob.length; i++) {
63
+ const ch = glob[i];
64
+ if (ch === "*" && glob[i + 1] === "*") {
65
+ re += glob[i + 2] === "/" ? "(?:.*/)?" : ".*";
66
+ i += glob[i + 2] === "/" ? 2 : 1;
67
+ } else if (ch === "*") re += "[^/]*";
68
+ else if (ch === "?") re += "[^/]";
69
+ else re += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
70
+ }
71
+ return new RegExp(glob.includes("/") ? `^${re.replace(/^\.\//, "")}$` : `(^|/)${re}$`);
72
+ }
73
+ async function walk(dir, out) {
74
+ let entries;
75
+ try {
76
+ entries = await readdir(dir, { withFileTypes: true });
77
+ } catch {
78
+ return;
79
+ }
80
+ for (const entry of entries) {
81
+ if (entry.name === "node_modules") continue;
82
+ const full = join(dir, entry.name);
83
+ if (entry.isDirectory()) await walk(full, out);
84
+ else if (entry.isFile()) out.push(full);
85
+ }
86
+ }
87
+ function staticRoots(dir) {
88
+ for (let current = dirname(dir); dirname(current) !== current; current = dirname(current)) {
89
+ if (existsSync(join(current, "package.json"))) return ["public", "static", "src"].map((name) => join(current, name));
90
+ }
91
+ return [];
92
+ }
93
+ async function verifyDir(dir, options = {}) {
94
+ const root = resolve(dir);
95
+ const env = options.env ?? process.env;
96
+ const files = [];
97
+ await walk(root, files);
98
+ files.sort();
99
+ const relPath = (path) => relative(root, path).split(sep).join("/");
100
+ const ignore = (options.ignore ?? []).map(globToRegExp);
101
+ const roots = staticRoots(root);
102
+ const result = {
103
+ dir: root,
104
+ ok: true,
105
+ bundles: [],
106
+ maps: [],
107
+ ...options.server ? { server: true } : {},
108
+ upload: { status: "unverified", endpoint: null, reason: null, checked: 0, missing: 0 },
109
+ failures: []
110
+ };
111
+ const fail = (path, reason) => result.failures.push({ path, reason });
112
+ for (const file of files) {
113
+ const path = relPath(file);
114
+ if (file.endsWith(".map")) {
115
+ result.maps.push(path);
116
+ if (!options.allowMaps && !options.server) {
117
+ fail(path, "source map in the deploy output: it exposes your original source. Delete it after upload (upload --delete-after-upload, or the bundler plugin) or keep it out of the deploy");
118
+ }
119
+ continue;
120
+ }
121
+ if (!BUNDLE_RE.test(file)) continue;
122
+ const bytes = await readFile(file);
123
+ const bundle = { path, status: "ok", debugId: null, reasons: [], uploaded: null };
124
+ result.bundles.push(bundle);
125
+ const skip = (reason) => {
126
+ bundle.status = "skipped";
127
+ bundle.reasons.push(reason);
128
+ };
129
+ if (ignore.some((re) => re.test(path))) {
130
+ skip("matches --ignore");
131
+ continue;
132
+ }
133
+ const known = NOT_BUNDLES.find(([re]) => re.test(path));
134
+ if (known) {
135
+ skip(known[1]);
136
+ continue;
137
+ }
138
+ let copied = null;
139
+ for (const staticRoot of roots) {
140
+ const candidate = join(staticRoot, path);
141
+ if (existsSync(candidate) && (await readFile(candidate)).equals(bytes)) copied = relative(dirname(staticRoot), candidate).split(sep).join("/");
142
+ }
143
+ if (copied) {
144
+ skip(`copied unchanged from ${copied}, not built`);
145
+ continue;
146
+ }
147
+ const code = bytes.toString("utf8");
148
+ const commentId = readDebugIdComment(code);
149
+ const snippetId = SNIPPET_ID_RE.exec(code)?.[1] ?? null;
150
+ bundle.debugId = commentId;
151
+ if (!commentId && !hasDebugIdSnippet(code)) {
152
+ bundle.reasons.push(
153
+ "no debug id: its errors can't be matched to a source map. Run `autter-runtime sourcemaps inject` on the build output (or use the bundler plugin with AUTTER_RUNTIME_KEY set) before deploying"
154
+ );
155
+ } else if (!commentId) {
156
+ bundle.reasons.push("has the debug id snippet but no //# debugId= comment: run `autter-runtime sourcemaps inject` on it again");
157
+ } else if (!hasDebugIdSnippet(code)) {
158
+ bundle.reasons.push(
159
+ "has a //# debugId= comment but no registration snippet, so the SDK can't report its id: run `autter-runtime sourcemaps inject` on it"
160
+ );
161
+ } else if (snippetId && snippetId !== commentId) {
162
+ bundle.reasons.push(`its snippet registers debug id ${snippetId} but its comment says ${commentId}: run inject on the original build output`);
163
+ }
164
+ const url = readSourceMappingUrl(code);
165
+ if (url?.startsWith("data:")) {
166
+ if (!options.server) {
167
+ bundle.reasons.push("carries an inline source map (data: URL): your original source ships with the bundle. Use hidden or external maps");
168
+ }
169
+ } else if (url && !/^[a-z][\w+.-]*:/i.test(url) && !url.startsWith("/")) {
170
+ let target = url.split(/[?#]/)[0];
171
+ try {
172
+ target = decodeURIComponent(target);
173
+ } catch {
174
+ }
175
+ if (!existsSync(resolve(dirname(file), target))) {
176
+ bundle.reasons.push(
177
+ `its sourceMappingURL points at ${url}, which is not in the output (browsers' devtools request it and get a 404). Remove the comment: upload --delete-after-upload does`
178
+ );
179
+ }
180
+ }
181
+ if (bundle.reasons.length) {
182
+ bundle.status = "failed";
183
+ for (const reason of bundle.reasons) fail(path, reason);
184
+ }
185
+ }
186
+ const counted = result.bundles.filter((b) => b.status !== "skipped");
187
+ if (!counted.length) fail(".", `no .js/.mjs/.cjs bundles under ${dir}: is this the build output?`);
188
+ await checkUploads(result, counted, options, env);
189
+ result.ok = result.failures.length === 0;
190
+ return result;
191
+ }
192
+ async function checkUploads(result, bundles, options, env) {
193
+ const upload = result.upload;
194
+ const key = (options.key ?? env.AUTTER_RUNTIME_KEY ?? "").trim();
195
+ if (!key) {
196
+ upload.reason = "AUTTER_RUNTIME_KEY is not set: only the local checks ran";
197
+ return;
198
+ }
199
+ upload.endpoint = resolveEndpoint(options.endpoint, env);
200
+ if (key.startsWith(CLIENT_KEY_PREFIX)) {
201
+ upload.status = "error";
202
+ upload.reason = "AUTTER_RUNTIME_KEY is a publishable client key (autter_rtc_\u2026), which can't check source maps: use an upload key (autter_rtu_\u2026) or the server key (autter_rt_\u2026)";
203
+ result.failures.push({ path: ".", reason: upload.reason });
204
+ return;
205
+ }
206
+ const withIds = bundles.filter((b) => b.debugId);
207
+ if (!withIds.length) {
208
+ upload.reason = "no bundle has a debug id to check";
209
+ return;
210
+ }
211
+ let release = "verify";
212
+ try {
213
+ release = resolveRelease(options.release, env, options.cwd).release;
214
+ } catch {
215
+ }
216
+ const doFetch = options.fetch ?? fetch;
217
+ const missing = [];
218
+ for (let start = 0; start < withIds.length; start += CHECK_BATCH) {
219
+ const batch = withIds.slice(start, start + CHECK_BATCH);
220
+ let res;
221
+ try {
222
+ res = await doFetch(`${upload.endpoint}/v1/sourcemaps/check`, {
223
+ method: "POST",
224
+ headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
225
+ body: JSON.stringify({ release, files: batch.map((b) => ({ filename: servedFilename(options.urlPrefix, b.path), debugId: b.debugId })) })
226
+ });
227
+ } catch (err) {
228
+ upload.status = "error";
229
+ upload.reason = `could not reach the ingester: ${err.message}`;
230
+ result.failures.push({ path: ".", reason: upload.reason });
231
+ return;
232
+ }
233
+ if (res.status === 404 || res.status === 400) {
234
+ upload.status = "unverified";
235
+ upload.reason = res.status === 404 ? "the ingester predates 1.6.0 (no /v1/sourcemaps/check), so uploads can't be checked: upgrade it" : "the ingester predates 1.7.0, which checks maps by debug id alone, so uploads can't be checked after the maps were deleted: upgrade it";
236
+ return;
237
+ }
238
+ if (res.status === 401 || res.status === 403) {
239
+ upload.status = "error";
240
+ upload.reason = `the ingester rejected the key (${res.status}): ${(await res.text()).slice(0, 300)}` + (key.startsWith(UPLOAD_KEY_PREFIX) ? " (upload keys, autter_rtu_\u2026, need ingester 1.7.0 or later)" : "");
241
+ result.failures.push({ path: ".", reason: upload.reason });
242
+ return;
243
+ }
244
+ if (!res.ok) {
245
+ upload.status = "error";
246
+ upload.reason = `the source map check failed: HTTP ${res.status}`;
247
+ result.failures.push({ path: ".", reason: upload.reason });
248
+ return;
249
+ }
250
+ const body = await res.json();
251
+ const present = new Set(Array.isArray(body.present) ? body.present : []);
252
+ batch.forEach((bundle, index) => {
253
+ bundle.uploaded = present.has(index);
254
+ if (!bundle.uploaded) missing.push(bundle);
255
+ });
256
+ }
257
+ upload.checked = withIds.length;
258
+ upload.missing = missing.length;
259
+ upload.status = missing.length ? "missing" : "verified";
260
+ upload.reason = missing.length ? `${missing.length} of ${withIds.length} bundle(s) have no map on the ingester` : null;
261
+ for (const bundle of missing) {
262
+ const reason = `no map with debug id ${bundle.debugId} on the ingester for this key's repository: upload this build's maps (autter-runtime sourcemaps upload, or the bundler plugin with AUTTER_RUNTIME_KEY set)`;
263
+ bundle.status = "failed";
264
+ bundle.reasons.push(reason);
265
+ result.failures.push({ path: bundle.path, reason });
266
+ }
267
+ }
268
+ function formatVerify(result) {
269
+ const lines = [];
270
+ for (const bundle of result.bundles) {
271
+ if (bundle.status === "ok") lines.push(`ok ${bundle.path} (debug id ${bundle.debugId}${bundle.uploaded ? ", map uploaded" : ""})`);
272
+ else if (bundle.status === "skipped") lines.push(`skipped ${bundle.path}: ${bundle.reasons.join("; ")}`);
273
+ else for (const reason of bundle.reasons) lines.push(`FAILED ${bundle.path}: ${reason}`);
274
+ }
275
+ for (const map of result.maps) {
276
+ const failure = result.failures.find((f) => f.path === map);
277
+ lines.push(
278
+ failure ? `FAILED ${map}: ${failure.reason}` : result.server ? `note ${map}: source map in the server output (browsers never load it)` : `warning ${map}: source map in the output (allowed by --allow-maps; remove it before deploying)`
279
+ );
280
+ }
281
+ for (const failure of result.failures.filter((f) => f.path === ".")) lines.push(`FAILED ${failure.reason}`);
282
+ const u = result.upload;
283
+ lines.push(
284
+ u.status === "verified" ? `upload: verified, ${u.checked} bundle map(s) on the ingester (${u.endpoint})` : u.status === "missing" ? `upload: ${u.reason} (${u.endpoint})` : `upload: ${u.status}${u.reason ? `, ${u.reason}` : ""}`
285
+ );
286
+ const counted = result.bundles.filter((b) => b.status !== "skipped");
287
+ lines.push(
288
+ result.ok ? `ok: ${counted.length} bundle(s) with debug ids, ${result.maps.length ? `${result.maps.length} source map(s) left (${result.server ? "server output" : "--allow-maps"})` : "no source maps left"}${u.status === "unverified" ? ", upload not verified" : ""}` : `${result.failures.length} problem(s) in ${result.dir}`
289
+ );
290
+ return lines;
291
+ }
37
292
  export {
38
293
  BUNDLE_RE,
294
+ CLIENT_KEY_PREFIX,
39
295
  DEBUG_ID_RE,
40
296
  DEBUG_ID_REGISTRY,
41
297
  DEFAULT_ENDPOINT,
42
298
  FatalUploadError,
299
+ KEY_ADVICE,
43
300
  MAX_MAP_CHARS,
44
301
  MAX_UPLOAD_BYTES,
45
302
  RELEASE_ENV_VARS,
46
303
  RELEASE_RE,
47
304
  SCOPES_KEY,
48
305
  SCOPES_VERSION,
306
+ SERVER_KEY_PREFIX,
49
307
  SNIPPET_LINE_KEY,
308
+ UPLOAD_KEY_PREFIX,
50
309
  computeScopes,
51
310
  debugIdFor,
52
311
  debugIdSnippet,
53
312
  findBundles,
54
313
  formatUploadSummary,
314
+ formatVerify,
55
315
  gitHead,
316
+ globToRegExp,
56
317
  hasDebugIdSnippet,
57
318
  injectBundle,
58
319
  injectDir,
320
+ isInAppSource,
59
321
  mapPathFor,
60
322
  normalizeDebugId,
61
323
  processBuildOutput,
@@ -64,9 +326,12 @@ export {
64
326
  resolveEndpoint,
65
327
  resolveRelease,
66
328
  servedFilename,
329
+ serverUrlPrefix,
67
330
  shiftMappings,
68
331
  snippetLine,
69
332
  storedMapJson,
333
+ storedSourcesContent,
70
334
  stripSourceMappingUrl,
71
- uploadDir
335
+ uploadDir,
336
+ verifyDir
72
337
  };