@autter/runtime-cli 0.0.0-stage → 1.1.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.cjs ADDED
@@ -0,0 +1,1079 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ BUNDLE_RE: () => BUNDLE_RE,
24
+ DEBUG_ID_RE: () => DEBUG_ID_RE,
25
+ DEBUG_ID_REGISTRY: () => DEBUG_ID_REGISTRY,
26
+ DEFAULT_ENDPOINT: () => DEFAULT_ENDPOINT,
27
+ FatalUploadError: () => FatalUploadError,
28
+ MAX_MAP_CHARS: () => MAX_MAP_CHARS,
29
+ MAX_UPLOAD_BYTES: () => MAX_UPLOAD_BYTES,
30
+ RELEASE_ENV_VARS: () => RELEASE_ENV_VARS,
31
+ RELEASE_RE: () => RELEASE_RE,
32
+ SCOPES_KEY: () => SCOPES_KEY,
33
+ SCOPES_VERSION: () => SCOPES_VERSION,
34
+ SNIPPET_LINE_KEY: () => SNIPPET_LINE_KEY,
35
+ computeScopes: () => computeScopes,
36
+ debugIdFor: () => debugIdFor,
37
+ debugIdSnippet: () => debugIdSnippet,
38
+ findBundles: () => findBundles,
39
+ formatUploadSummary: () => formatUploadSummary,
40
+ gitHead: () => gitHead,
41
+ hasDebugIdSnippet: () => hasDebugIdSnippet,
42
+ injectBundle: () => injectBundle,
43
+ injectDir: () => injectDir,
44
+ mapPathFor: () => mapPathFor,
45
+ normalizeDebugId: () => normalizeDebugId,
46
+ processBuildOutput: () => processBuildOutput,
47
+ readDebugIdComment: () => readDebugIdComment,
48
+ readSourceMappingUrl: () => readSourceMappingUrl,
49
+ resolveEndpoint: () => resolveEndpoint,
50
+ resolveRelease: () => resolveRelease,
51
+ servedFilename: () => servedFilename,
52
+ shiftMappings: () => shiftMappings,
53
+ snippetLine: () => snippetLine,
54
+ storedMapJson: () => storedMapJson,
55
+ stripSourceMappingUrl: () => stripSourceMappingUrl,
56
+ uploadDir: () => uploadDir
57
+ });
58
+ module.exports = __toCommonJS(src_exports);
59
+
60
+ // src/debug-id.ts
61
+ var import_node_crypto = require("crypto");
62
+ var DEBUG_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
63
+ function normalizeDebugId(value) {
64
+ if (typeof value !== "string") return null;
65
+ const id = value.trim().toLowerCase();
66
+ return DEBUG_ID_RE.test(id) ? id : null;
67
+ }
68
+ function debugIdFor(bytes) {
69
+ const hash = (0, import_node_crypto.createHash)("sha256").update(bytes).digest();
70
+ hash[6] = hash[6] & 15 | 64;
71
+ hash[8] = hash[8] & 63 | 128;
72
+ const hex = hash.subarray(0, 16).toString("hex");
73
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
74
+ }
75
+ var DEBUG_ID_COMMENT_RE = /^\/\/# debugId=([0-9a-fA-F-]{36})[ \t]*\r?$/gm;
76
+ function readDebugIdComment(code) {
77
+ let found = null;
78
+ for (const match of code.matchAll(DEBUG_ID_COMMENT_RE)) found = normalizeDebugId(match[1]) ?? found;
79
+ return found;
80
+ }
81
+ var DEBUG_ID_REGISTRY = "_autterDebugIds";
82
+ function debugIdSnippet(id) {
83
+ return `;!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},s=(new g.Error).stack;s&&((g.${DEBUG_ID_REGISTRY}=g.${DEBUG_ID_REGISTRY}||{})[s]="${id}")}catch(e){}}();`;
84
+ }
85
+ var SNIPPET_RE = /\(g\._autterDebugIds=g\._autterDebugIds\|\|\{\}\)\[s\]="[0-9a-f]{8}-/;
86
+ function hasDebugIdSnippet(code) {
87
+ return SNIPPET_RE.test(code);
88
+ }
89
+
90
+ // src/files.ts
91
+ var import_node_fs = require("fs");
92
+ var import_promises = require("fs/promises");
93
+ var import_node_path = require("path");
94
+ var BUNDLE_RE = /\.[cm]?js$/;
95
+ var SOURCE_MAPPING_URL_RE = /^[ \t]*\/\/[#@] sourceMappingURL=([^\s'"]+)[ \t]*\r?$/gm;
96
+ function readSourceMappingUrl(code) {
97
+ let found = null;
98
+ for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) found = match[1];
99
+ return found;
100
+ }
101
+ function stripSourceMappingUrl(code) {
102
+ const lines = code.split("\n");
103
+ for (let i = lines.length - 1; i >= 0; i--) {
104
+ const line = lines[i].trim();
105
+ if (line === "") continue;
106
+ if (/^\/\/[#@] sourceMappingURL=/.test(line)) {
107
+ lines.splice(i, 1);
108
+ return lines.join("\n");
109
+ }
110
+ if (!line.startsWith("//#")) break;
111
+ }
112
+ return code;
113
+ }
114
+ function mapPathFor(js, code) {
115
+ const url = readSourceMappingUrl(code);
116
+ if (url && !/^[a-z][\w+.-]*:/i.test(url) && !url.startsWith("/")) {
117
+ let decoded = url.split(/[?#]/)[0];
118
+ try {
119
+ decoded = decodeURIComponent(decoded);
120
+ } catch {
121
+ }
122
+ const candidate = (0, import_node_path.resolve)((0, import_node_path.dirname)(js), decoded);
123
+ if ((0, import_node_fs.existsSync)(candidate)) return candidate;
124
+ }
125
+ const sibling = `${js}.map`;
126
+ return (0, import_node_fs.existsSync)(sibling) ? sibling : null;
127
+ }
128
+ async function walk(dir, out, pattern = BUNDLE_RE) {
129
+ let entries;
130
+ try {
131
+ entries = await (0, import_promises.readdir)(dir, { withFileTypes: true });
132
+ } catch {
133
+ return;
134
+ }
135
+ for (const entry of entries) {
136
+ if (entry.name === "node_modules") continue;
137
+ const full = (0, import_node_path.join)(dir, entry.name);
138
+ if (entry.isDirectory()) await walk(full, out, pattern);
139
+ else if (entry.isFile() && pattern.test(entry.name)) out.push(full);
140
+ }
141
+ }
142
+ var CSS_SOURCE_MAPPING_URL_RE = /\/\*[#@] sourceMappingURL=([^\s*]+)\s*\*\/\s*$/;
143
+ function pointsAt(file, url, map) {
144
+ if (!url || /^[a-z][\w+.-]*:/i.test(url) || url.startsWith("/")) return false;
145
+ let path = url.split(/[?#]/)[0];
146
+ try {
147
+ path = decodeURIComponent(path);
148
+ } catch {
149
+ }
150
+ return (0, import_node_path.resolve)((0, import_node_path.dirname)(file), path) === map;
151
+ }
152
+ async function stripReference(file, map) {
153
+ let code;
154
+ try {
155
+ code = await (0, import_promises.readFile)(file, "utf8");
156
+ } catch {
157
+ return;
158
+ }
159
+ let stripped = code;
160
+ if (BUNDLE_RE.test(file)) {
161
+ if (pointsAt(file, readSourceMappingUrl(code), map)) stripped = stripSourceMappingUrl(code);
162
+ } else if (file.endsWith(".css")) {
163
+ const match = CSS_SOURCE_MAPPING_URL_RE.exec(code);
164
+ if (match && pointsAt(file, match[1], map)) stripped = code.slice(0, match.index).replace(/\n?$/, "\n");
165
+ }
166
+ if (stripped !== code) await (0, import_promises.writeFile)(file, stripped);
167
+ }
168
+ async function removeSourceMaps(maps, owners = /* @__PURE__ */ new Map()) {
169
+ const removed = [];
170
+ for (const map of [...new Set(maps)].sort()) {
171
+ if (!(0, import_node_fs.existsSync)(map)) continue;
172
+ await (0, import_promises.rm)(map, { force: true });
173
+ removed.push(map);
174
+ const owner = owners.get(map) ?? map.replace(/\.map$/, "");
175
+ await stripReference(owner, map);
176
+ }
177
+ return removed;
178
+ }
179
+ async function findBundles(dir, files) {
180
+ const root = (0, import_node_path.resolve)(dir);
181
+ const candidates = [];
182
+ if (files) {
183
+ for (const file of files) if (BUNDLE_RE.test(file)) candidates.push((0, import_node_path.resolve)(root, file));
184
+ } else {
185
+ await walk(root, candidates);
186
+ }
187
+ const bundles = [];
188
+ for (const js of [...new Set(candidates)].sort()) {
189
+ let code;
190
+ try {
191
+ code = await (0, import_promises.readFile)(js, "utf8");
192
+ } catch {
193
+ continue;
194
+ }
195
+ const map = mapPathFor(js, code);
196
+ if (map) bundles.push({ js, map, path: (0, import_node_path.relative)(root, js).split(import_node_path.sep).join("/") });
197
+ }
198
+ return bundles;
199
+ }
200
+
201
+ // src/inject.ts
202
+ var import_promises2 = require("fs/promises");
203
+ var SNIPPET_LINE_KEY = "x_autter_snippet_line";
204
+ function snippetLine(code) {
205
+ let line = 0;
206
+ let i = 0;
207
+ if (code.startsWith("#!")) {
208
+ const nl = code.indexOf("\n");
209
+ if (nl < 0) return -1;
210
+ line = 1;
211
+ i = nl + 1;
212
+ }
213
+ for (; ; ) {
214
+ while (i < code.length && /\s/.test(code[i])) i++;
215
+ if (code.startsWith("//", i)) {
216
+ const nl = code.indexOf("\n", i);
217
+ if (nl < 0) return -1;
218
+ i = nl + 1;
219
+ } else if (code.startsWith("/*", i)) {
220
+ const end = code.indexOf("*/", i + 2);
221
+ if (end < 0) return -1;
222
+ i = end + 2;
223
+ } else {
224
+ break;
225
+ }
226
+ }
227
+ return code[i] === '"' || code[i] === "'" ? -1 : line;
228
+ }
229
+ function shiftMappings(mappings, at, count = 1) {
230
+ const lines = mappings.split(";");
231
+ while (lines.length < at) lines.push("");
232
+ lines.splice(at, 0, ...Array(count).fill(""));
233
+ return lines.join(";");
234
+ }
235
+ function insertBeforeTrailingComments(code, text) {
236
+ const lines = code.split("\n");
237
+ let at = lines.length;
238
+ while (at > 0) {
239
+ const line = lines[at - 1].trim();
240
+ if (line === "" || line.startsWith("//#") || line.startsWith("//@")) at--;
241
+ else break;
242
+ }
243
+ const head = lines.slice(0, at).join("\n");
244
+ const tail = lines.slice(at).join("\n");
245
+ return `${head}${head && !head.endsWith("\n") ? "\n" : ""}${text}${tail ? `
246
+ ${tail.replace(/^\n+/, "")}` : "\n"}`;
247
+ }
248
+ async function injectBundle(bundle, options = {}) {
249
+ const bytes = await (0, import_promises2.readFile)(bundle.js);
250
+ const code = bytes.toString("utf8");
251
+ const base = { path: bundle.path, js: bundle.js, map: bundle.map };
252
+ let map;
253
+ try {
254
+ map = JSON.parse(await (0, import_promises2.readFile)(bundle.map, "utf8"));
255
+ if (!map || typeof map !== "object") throw new Error("not an object");
256
+ } catch {
257
+ return { ...base, debugId: "", status: "invalid-map" };
258
+ }
259
+ const existing = readDebugIdComment(code);
260
+ const hasSnippet = hasDebugIdSnippet(code);
261
+ const debugId = existing ?? debugIdFor(bytes);
262
+ let out = code;
263
+ let mapDirty = false;
264
+ if (!hasSnippet) {
265
+ const shifted = typeof map[SNIPPET_LINE_KEY] === "number" ? map[SNIPPET_LINE_KEY] : null;
266
+ const line = shifted ?? snippetLine(code);
267
+ if (line >= 0 && (shifted !== null || typeof map.mappings === "string" && !("sections" in map))) {
268
+ let offset = 0;
269
+ for (let n = 0; n < line; n++) offset = out.indexOf("\n", offset) + 1;
270
+ out = `${out.slice(0, offset)}${debugIdSnippet(debugId)}
271
+ ${out.slice(offset)}`;
272
+ if (shifted === null) {
273
+ map.mappings = shiftMappings(map.mappings, line);
274
+ map[SNIPPET_LINE_KEY] = line;
275
+ mapDirty = true;
276
+ }
277
+ } else {
278
+ out = insertBeforeTrailingComments(out, debugIdSnippet(debugId));
279
+ }
280
+ }
281
+ if (!existing) out = `${out}${out.endsWith("\n") ? "" : "\n"}//# debugId=${debugId}
282
+ `;
283
+ if (options.stripSourceMappingUrl) out = stripSourceMappingUrl(out);
284
+ if (map.debugId !== debugId) {
285
+ map.debugId = debugId;
286
+ mapDirty = true;
287
+ }
288
+ const changed = mapDirty || out !== code;
289
+ if (changed && !options.dryRun) {
290
+ if (mapDirty) await (0, import_promises2.writeFile)(bundle.map, JSON.stringify(map));
291
+ if (out !== code) await (0, import_promises2.writeFile)(bundle.js, out);
292
+ }
293
+ return { ...base, debugId, status: changed ? "injected" : "unchanged" };
294
+ }
295
+ async function injectDir(dir, options = {}) {
296
+ const results = [];
297
+ for (const bundle of await findBundles(dir, options.files)) results.push(await injectBundle(bundle, options));
298
+ return results;
299
+ }
300
+
301
+ // src/upload.ts
302
+ var import_node_crypto2 = require("crypto");
303
+ var import_promises3 = require("fs/promises");
304
+ var import_node_util = require("util");
305
+ var import_node_zlib = require("zlib");
306
+
307
+ // src/release.ts
308
+ var import_node_child_process = require("child_process");
309
+ var RELEASE_RE = /^[a-zA-Z0-9._-]{1,200}$/;
310
+ var RELEASE_ENV_VARS = [
311
+ "GITHUB_SHA",
312
+ "VERCEL_GIT_COMMIT_SHA",
313
+ "CF_PAGES_COMMIT_SHA",
314
+ "GIT_SHA"
315
+ ];
316
+ function gitHead(cwd = process.cwd()) {
317
+ try {
318
+ const sha = (0, import_node_child_process.execFileSync)("git", ["rev-parse", "HEAD"], {
319
+ cwd,
320
+ encoding: "utf8",
321
+ stdio: ["ignore", "pipe", "ignore"],
322
+ timeout: 1e4
323
+ }).trim();
324
+ return /^[0-9a-f]{7,64}$/.test(sha) ? sha : null;
325
+ } catch {
326
+ return null;
327
+ }
328
+ }
329
+ function resolveRelease(explicit, env = process.env, cwd = process.cwd()) {
330
+ const candidates = [
331
+ ["--release", explicit],
332
+ ...RELEASE_ENV_VARS.map((name) => [name, env[name]])
333
+ ];
334
+ for (const [source, value] of candidates) {
335
+ const release = value?.trim();
336
+ if (!release) continue;
337
+ if (!RELEASE_RE.test(release)) {
338
+ throw new Error(
339
+ `release "${release}" (from ${source}) is not valid: use 1-200 letters, digits, ".", "_" or "-" (a commit SHA works)`
340
+ );
341
+ }
342
+ return { release, source };
343
+ }
344
+ const head = gitHead(cwd);
345
+ if (head) return { release: head, source: "git" };
346
+ throw new Error(
347
+ `no release: pass --release <release>, or set one of ${RELEASE_ENV_VARS.join(", ")}, or run inside a git checkout`
348
+ );
349
+ }
350
+
351
+ // src/scopes.ts
352
+ var import_acorn = require("acorn");
353
+ var SCOPES_KEY = "x_autter_scopes";
354
+ var SCOPES_VERSION = 1;
355
+ var BASE_OPTIONS = {
356
+ ecmaVersion: "latest",
357
+ allowHashBang: true,
358
+ allowReturnOutsideFunction: true,
359
+ allowReserved: true
360
+ };
361
+ function parseBundle(code) {
362
+ try {
363
+ return (0, import_acorn.parse)(code, {
364
+ ...BASE_OPTIONS,
365
+ sourceType: "module",
366
+ allowAwaitOutsideFunction: true,
367
+ allowImportExportEverywhere: true
368
+ });
369
+ } catch (moduleError) {
370
+ try {
371
+ return (0, import_acorn.parse)(code, { ...BASE_OPTIONS, sourceType: "script" });
372
+ } catch (scriptError) {
373
+ const pos = (err) => typeof err.pos === "number" ? err.pos : -1;
374
+ throw pos(scriptError) > pos(moduleError) ? scriptError : moduleError;
375
+ }
376
+ }
377
+ }
378
+ function isNode(value) {
379
+ return typeof value === "object" && value !== null && typeof value.type === "string";
380
+ }
381
+ var IDENTIFIER_NAME_RE = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
382
+ function identifierToken(node) {
383
+ if (!isNode(node)) return null;
384
+ if (node.type === "Identifier") return { offset: node.start, name: node.name, literal: false };
385
+ if (node.type === "PrivateIdentifier") return { offset: node.start, name: `#${node.name}`, literal: false };
386
+ return null;
387
+ }
388
+ function literalToken(node) {
389
+ if (!isNode(node) || node.type !== "Literal" || typeof node.value !== "string") return null;
390
+ return IDENTIFIER_NAME_RE.test(node.value) ? { offset: node.start, name: node.value, literal: true } : null;
391
+ }
392
+ function keyToken(property) {
393
+ if (!property.computed) {
394
+ const id = identifierToken(property.key);
395
+ if (id) return id;
396
+ }
397
+ return literalToken(property.key);
398
+ }
399
+ function bindingToken(target) {
400
+ if (!isNode(target)) return null;
401
+ if (target.type === "Identifier") return identifierToken(target);
402
+ if (target.type === "MemberExpression") {
403
+ return target.computed ? literalToken(target.property) : identifierToken(target.property);
404
+ }
405
+ return null;
406
+ }
407
+ function contextTokens(node, parent) {
408
+ let token = null;
409
+ switch (parent?.type) {
410
+ case "VariableDeclarator":
411
+ if (parent.init === node) token = bindingToken(parent.id);
412
+ break;
413
+ case "AssignmentExpression":
414
+ case "AssignmentPattern":
415
+ if (parent.right === node) token = bindingToken(parent.left);
416
+ break;
417
+ case "Property":
418
+ case "PropertyDefinition":
419
+ case "MethodDefinition":
420
+ if (parent.value === node) token = keyToken(parent);
421
+ break;
422
+ }
423
+ return token ? [token] : [];
424
+ }
425
+ function classTokens(path) {
426
+ if (!path || path.node.type !== "ClassDeclaration" && path.node.type !== "ClassExpression") return [];
427
+ const own = identifierToken(path.node.id);
428
+ return [...own ? [own] : [], ...contextTokens(path.node, path.parent?.node)];
429
+ }
430
+ function describe(path) {
431
+ const fn = path.node;
432
+ const parent = path.parent?.node;
433
+ const own = identifierToken(fn.id);
434
+ const isMethod = parent?.type === "MethodDefinition" || parent?.type === "Property" && parent.value === fn && (parent.method === true || parent.kind !== "init");
435
+ let context;
436
+ if (parent?.type === "MethodDefinition" && parent.kind === "constructor") {
437
+ context = classTokens(path.parent?.parent?.parent ?? null);
438
+ } else {
439
+ context = contextTokens(fn, parent);
440
+ }
441
+ return {
442
+ start: fn.start,
443
+ end: fn.end,
444
+ own,
445
+ recoverAt: !own && fn.type !== "ArrowFunctionExpression" && !isMethod ? fn.start : null,
446
+ context
447
+ };
448
+ }
449
+ var FUNCTION_TYPES = /* @__PURE__ */ new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
450
+ function classInitializer(path) {
451
+ const node = path.node;
452
+ let range = null;
453
+ if (node.type === "StaticBlock") range = node;
454
+ else if (node.type === "PropertyDefinition" && isNode(node.value) && !FUNCTION_TYPES.has(node.value.type)) range = node.value;
455
+ if (!range) return null;
456
+ return { start: range.start, end: range.end, own: null, recoverAt: null, context: classTokens(path.parent?.parent ?? null) };
457
+ }
458
+ function collectFunctions(program) {
459
+ const found = [];
460
+ const stack = [{ node: program, parent: null }];
461
+ for (let path = stack.pop(); path; path = stack.pop()) {
462
+ const node = path.node;
463
+ if (FUNCTION_TYPES.has(node.type)) found.push(describe(path));
464
+ else {
465
+ const initializer = classInitializer(path);
466
+ if (initializer) found.push(initializer);
467
+ }
468
+ for (const key in node) {
469
+ const value = node[key];
470
+ if (Array.isArray(value)) {
471
+ for (let i = value.length - 1; i >= 0; i--) if (isNode(value[i])) stack.push({ node: value[i], parent: path });
472
+ } else if (isNode(value)) {
473
+ stack.push({ node: value, parent: path });
474
+ }
475
+ }
476
+ }
477
+ return found;
478
+ }
479
+ function lineStarts(code) {
480
+ const starts = [0];
481
+ for (let i = 0; i < code.length; i++) {
482
+ const c = code.charCodeAt(i);
483
+ if (c === 10 || c === 8232 || c === 8233) starts.push(i + 1);
484
+ else if (c === 13) {
485
+ if (code.charCodeAt(i + 1) === 10) i++;
486
+ starts.push(i + 1);
487
+ }
488
+ }
489
+ return starts;
490
+ }
491
+ function positionOf(starts, offset) {
492
+ let lo = 0;
493
+ let hi = starts.length - 1;
494
+ while (lo < hi) {
495
+ const mid = lo + hi + 1 >> 1;
496
+ if (starts[mid] <= offset) lo = mid;
497
+ else hi = mid - 1;
498
+ }
499
+ return [lo, offset - starts[lo]];
500
+ }
501
+ var BASE64 = new Int8Array(128).fill(-1);
502
+ for (const [i, ch] of [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].entries()) BASE64[ch.charCodeAt(0)] = i;
503
+ function findSegments(mappings, wanted) {
504
+ let line = 0;
505
+ let column = 0;
506
+ let source = 0;
507
+ let originalLine = 0;
508
+ let originalColumn = 0;
509
+ let name = 0;
510
+ let want = wanted.get(0);
511
+ const fields = [0, 0, 0, 0, 0];
512
+ let i = 0;
513
+ while (i < mappings.length) {
514
+ const ch = mappings.charCodeAt(i);
515
+ if (ch === 59) {
516
+ line++;
517
+ column = 0;
518
+ want = wanted.get(line);
519
+ i++;
520
+ continue;
521
+ }
522
+ if (ch === 44) {
523
+ i++;
524
+ continue;
525
+ }
526
+ let count = 0;
527
+ while (i < mappings.length) {
528
+ const next = mappings.charCodeAt(i);
529
+ if (next === 44 || next === 59) break;
530
+ let value = 0;
531
+ let shift = 0;
532
+ let digit;
533
+ do {
534
+ const code = mappings.charCodeAt(i++);
535
+ digit = code < 128 ? BASE64[code] : -1;
536
+ if (digit < 0 || shift > 30) throw new Error("invalid mappings");
537
+ value |= (digit & 31) << shift;
538
+ shift += 5;
539
+ } while (digit & 32);
540
+ const decoded = value & 1 ? -(value >>> 1) : value >>> 1;
541
+ if (count < 5) fields[count] = decoded;
542
+ count++;
543
+ }
544
+ column += fields[0];
545
+ if (count >= 4) {
546
+ source += fields[1];
547
+ originalLine += fields[2];
548
+ originalColumn += fields[3];
549
+ }
550
+ if (count >= 5) name += fields[4];
551
+ if (want && want.get(column) === null) {
552
+ want.set(column, {
553
+ source: count >= 4 ? source : -1,
554
+ line: originalLine,
555
+ column: originalColumn,
556
+ name: count >= 5 ? name : -1
557
+ });
558
+ }
559
+ }
560
+ }
561
+ function looksMangled(name) {
562
+ return name.replace(/^#/, "").length <= 2;
563
+ }
564
+ var IDENTIFIER_AT_RE = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/uy;
565
+ var OWN_NAME_AT_RE = /(?:async\s+)?function\b\s*\*?\s*([$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)/uy;
566
+ var NOT_A_NAME = new Set(
567
+ "abstract async await break case catch class const continue debugger declare default delete do else enum export extends false finally for function get if implements import in instanceof interface let new null of override package private protected public readonly return set static super switch this throw true try typeof var void while with yield".split(" ")
568
+ );
569
+ var NameResolver = class {
570
+ constructor(map, segmentAt) {
571
+ this.segmentAt = segmentAt;
572
+ this.names = Array.isArray(map.names) ? map.names : [];
573
+ this.sourcesContent = Array.isArray(map.sourcesContent) ? map.sourcesContent : [];
574
+ }
575
+ segmentAt;
576
+ names;
577
+ sourcesContent;
578
+ sourceLines = /* @__PURE__ */ new Map();
579
+ originalLine(segment) {
580
+ if (segment.source < 0) return null;
581
+ let lines = this.sourceLines.get(segment.source);
582
+ if (lines === void 0) {
583
+ const content = this.sourcesContent[segment.source];
584
+ lines = typeof content === "string" ? content.split(/\r\n|[\n\r\u2028\u2029]/) : null;
585
+ this.sourceLines.set(segment.source, lines);
586
+ }
587
+ return lines?.[segment.line] ?? null;
588
+ }
589
+ /** The original identifier at a segment's source position. */
590
+ identifierAt(segment, re, group = 0) {
591
+ const text = this.originalLine(segment);
592
+ if (text === null) return null;
593
+ re.lastIndex = segment.column;
594
+ const found = re.exec(text)?.[group];
595
+ return found && !NOT_A_NAME.has(found) ? found : null;
596
+ }
597
+ /** Original name of a token: the map's `names` at its exact position;
598
+ * else the generated name when it isn't mangled; else the identifier
599
+ * at the mapped position in `sourcesContent`. Null when unknown. */
600
+ resolve(token) {
601
+ if (token.literal) return token.name;
602
+ const segment = this.segmentAt(token.offset);
603
+ if (segment && segment.name >= 0) {
604
+ const name = this.names[segment.name];
605
+ if (typeof name === "string" && name) return name;
606
+ }
607
+ if (!looksMangled(token.name)) return token.name;
608
+ return segment ? this.identifierAt(segment, IDENTIFIER_AT_RE) : null;
609
+ }
610
+ /** The name a minifier removed from `function name() {}`, read from the
611
+ * original source at the function's mapped start. */
612
+ recover(offset) {
613
+ const segment = this.segmentAt(offset);
614
+ return segment ? this.identifierAt(segment, OWN_NAME_AT_RE, 1) : null;
615
+ }
616
+ };
617
+ var BASE64_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
618
+ function vlq(value) {
619
+ let rest = value < 0 ? -value << 1 | 1 : value << 1;
620
+ let out = "";
621
+ do {
622
+ let digit = rest & 31;
623
+ rest >>>= 5;
624
+ if (rest > 0) digit |= 32;
625
+ out += BASE64_DIGITS[digit];
626
+ } while (rest > 0);
627
+ return out;
628
+ }
629
+ function encodeScopes(entries) {
630
+ const parts = [];
631
+ let line = 0;
632
+ let previousStart = 0;
633
+ let previousName = 0;
634
+ let firstOnLine = true;
635
+ for (const [startLine, startColumn, endLine, endColumn, nameIndex] of entries) {
636
+ if (startLine > line) {
637
+ parts.push(";".repeat(startLine - line));
638
+ line = startLine;
639
+ previousStart = 0;
640
+ firstOnLine = true;
641
+ }
642
+ if (!firstOnLine) parts.push(",");
643
+ firstOnLine = false;
644
+ let segment = vlq(startColumn - previousStart) + vlq(endLine - startLine) + vlq(endLine === startLine ? endColumn - startColumn : endColumn);
645
+ previousStart = startColumn;
646
+ if (nameIndex >= 0) {
647
+ segment += vlq(nameIndex - previousName);
648
+ previousName = nameIndex;
649
+ }
650
+ parts.push(segment);
651
+ }
652
+ return parts.join("");
653
+ }
654
+ function computeScopes(code, map) {
655
+ try {
656
+ return scopesOf(code, map);
657
+ } catch (err) {
658
+ return { error: err instanceof Error ? err.message : String(err) };
659
+ }
660
+ }
661
+ function scopesOf(code, map) {
662
+ if (typeof map.mappings !== "string") return { error: "the map has no mappings string" };
663
+ let functions;
664
+ try {
665
+ functions = collectFunctions(parseBundle(code));
666
+ } catch (err) {
667
+ return { error: `could not parse the bundle: ${err instanceof Error ? err.message : String(err)}` };
668
+ }
669
+ const starts = lineStarts(code);
670
+ const wanted = /* @__PURE__ */ new Map();
671
+ const want = (offset) => {
672
+ const [line, column] = positionOf(starts, offset);
673
+ let columns = wanted.get(line);
674
+ if (!columns) wanted.set(line, columns = /* @__PURE__ */ new Map());
675
+ columns.set(column, null);
676
+ };
677
+ for (const fn of functions) {
678
+ if (fn.own && !fn.own.literal) want(fn.own.offset);
679
+ if (fn.recoverAt !== null) want(fn.recoverAt);
680
+ for (const token of fn.context) if (!token.literal) want(token.offset);
681
+ }
682
+ try {
683
+ findSegments(map.mappings, wanted);
684
+ } catch (err) {
685
+ return { error: `could not read the map: ${err instanceof Error ? err.message : String(err)}` };
686
+ }
687
+ const resolver = new NameResolver(map, (offset) => {
688
+ const [line, column] = positionOf(starts, offset);
689
+ return wanted.get(line)?.get(column) ?? null;
690
+ });
691
+ functions.sort((a, b) => a.start - b.start || b.end - a.end);
692
+ const mapNames = Array.isArray(map.names) ? map.names : [];
693
+ const nameIndex = /* @__PURE__ */ new Map();
694
+ mapNames.forEach((name, index) => {
695
+ if (typeof name === "string" && !nameIndex.has(name)) nameIndex.set(name, index);
696
+ });
697
+ const extraNames = [];
698
+ const indexOf = (name) => {
699
+ let index = nameIndex.get(name);
700
+ if (index === void 0) {
701
+ index = mapNames.length + extraNames.push(name) - 1;
702
+ nameIndex.set(name, index);
703
+ }
704
+ return index;
705
+ };
706
+ const entries = functions.map((fn) => {
707
+ let name = fn.own ? resolver.resolve(fn.own) : null;
708
+ if (name === null && fn.recoverAt !== null) name = resolver.recover(fn.recoverAt);
709
+ for (const token of fn.context) {
710
+ if (name !== null) break;
711
+ name = resolver.resolve(token);
712
+ }
713
+ const index = name !== null ? indexOf(name) : fn.own || fn.context.length > 0 ? indexOf(null) : -1;
714
+ const [startLine, startColumn] = positionOf(starts, fn.start);
715
+ const [endLine, endColumn] = positionOf(starts, fn.end);
716
+ return [startLine, startColumn, endLine, endColumn, index];
717
+ });
718
+ return { scopes: { version: SCOPES_VERSION, names: extraNames, scopes: encodeScopes(entries) } };
719
+ }
720
+
721
+ // src/upload.ts
722
+ var DEFAULT_ENDPOINT = "https://otlp.autter.dev";
723
+ var MAX_MAP_CHARS = 32 * 1024 * 1024;
724
+ var MAX_UPLOAD_BYTES = MAX_MAP_CHARS + 1024 * 1024;
725
+ var LEGACY_MAX_BYTES = 5 * 1024 * 1024;
726
+ var gzip = (0, import_node_util.promisify)(import_node_zlib.gzip);
727
+ var CHECK_BATCH = 500;
728
+ var MAX_ATTEMPTS = 3;
729
+ function resolveEndpoint(flag, env = process.env) {
730
+ const raw = flag || env.AUTTER_ENDPOINT || env.AUTTER_RUNTIME_ENDPOINT || env.OTEL_EXPORTER_OTLP_ENDPOINT || DEFAULT_ENDPOINT;
731
+ return raw.trim().replace(/\/+$/, "").replace(/\/v1\/[a-z-]+$/, "");
732
+ }
733
+ function servedFilename(urlPrefix, path) {
734
+ let prefix = (urlPrefix ?? "/").trim() || "/";
735
+ if (prefix.startsWith("~/")) prefix = prefix.slice(1);
736
+ if (!/^[a-z][\w+.-]*:\/\//i.test(prefix) && !prefix.startsWith("/")) prefix = `/${prefix}`;
737
+ return `${prefix.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
738
+ }
739
+ function storedMapJson(map) {
740
+ const { sourcesContent: _omitted, ...safe } = map;
741
+ return JSON.stringify(safe);
742
+ }
743
+ function bytesOf(buffer) {
744
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
745
+ }
746
+ function fits(json, body) {
747
+ return json.length <= MAX_MAP_CHARS && Buffer.byteLength(body) <= MAX_UPLOAD_BYTES;
748
+ }
749
+ function uploadBody(release, filename, debugId, json) {
750
+ return `{"release":${JSON.stringify(release)},"filename":${JSON.stringify(filename)},${debugId ? `"debugId":${JSON.stringify(debugId)},` : ""}"map":${json}}`;
751
+ }
752
+ async function prepare(bundle, urlPrefix, release, log, compress) {
753
+ let map;
754
+ try {
755
+ map = JSON.parse(await (0, import_promises3.readFile)(bundle.map, "utf8"));
756
+ } catch {
757
+ return { error: "map is not valid JSON" };
758
+ }
759
+ if (!map || map.version !== 3 || typeof map.mappings !== "string" || !Array.isArray(map.sources)) {
760
+ return { error: "not a version 3 source map with mappings and sources" };
761
+ }
762
+ const code = await (0, import_promises3.readFile)(bundle.js, "utf8");
763
+ const debugId = readDebugIdComment(code) ?? normalizeDebugId(map.debugId);
764
+ const filename = servedFilename(urlPrefix, bundle.path);
765
+ const { [SCOPES_KEY]: _stale, ...plain } = map;
766
+ const scopes = computeScopes(code, map);
767
+ let json = storedMapJson(plain);
768
+ if ("scopes" in scopes) {
769
+ const scoped = storedMapJson({ ...plain, [SCOPES_KEY]: scopes.scopes });
770
+ if (fits(scoped, uploadBody(release, filename, debugId, scoped))) json = scoped;
771
+ else if (fits(json, uploadBody(release, filename, debugId, json))) {
772
+ log(`warning: ${bundle.path}: its map is over 32 MB with function scopes, so it is uploaded without them (frames keep call-site names)`);
773
+ }
774
+ } else {
775
+ log(`warning: ${bundle.path}: no function scopes (${scopes.error}); its map is uploaded without them (frames keep call-site names)`);
776
+ }
777
+ const body = uploadBody(release, filename, debugId, json);
778
+ return {
779
+ bundle,
780
+ // Maps are text that compresses several times over; the ingester
781
+ // inflates the body (Content-Encoding: gzip).
782
+ body: compress && fits(json, body) ? bytesOf(await gzip(body)) : new Uint8Array(0),
783
+ path: bundle.path,
784
+ filename,
785
+ debugId,
786
+ hash: (0, import_node_crypto2.createHash)("sha256").update(json).digest("hex"),
787
+ bytes: Buffer.byteLength(body),
788
+ mapChars: json.length
789
+ };
790
+ }
791
+ var FatalUploadError = class extends Error {
792
+ };
793
+ function sleep(ms) {
794
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
795
+ }
796
+ async function uploadDir(dir, options = {}) {
797
+ const env = options.env ?? process.env;
798
+ const log = options.log ?? (() => {
799
+ });
800
+ const doFetch = options.fetch ?? fetch;
801
+ const { release, source: releaseSource } = resolveRelease(options.release, env, options.cwd);
802
+ const endpoint = resolveEndpoint(options.endpoint, env);
803
+ const summary = {
804
+ release,
805
+ releaseSource,
806
+ endpoint,
807
+ dryRun: Boolean(options.dryRun),
808
+ uploaded: [],
809
+ skipped: [],
810
+ failed: [],
811
+ legacyIngester: false,
812
+ deletedMaps: []
813
+ };
814
+ const items = [];
815
+ for (const bundle of await findBundles(dir, options.files)) {
816
+ const prepared = await prepare(bundle, options.urlPrefix, release, log, !options.dryRun);
817
+ if ("error" in prepared) {
818
+ summary.failed.push({ path: bundle.path, filename: servedFilename(options.urlPrefix, bundle.path), error: prepared.error });
819
+ } else if (prepared.mapChars > MAX_MAP_CHARS || prepared.bytes > MAX_UPLOAD_BYTES) {
820
+ summary.failed.push({
821
+ path: prepared.path,
822
+ filename: prepared.filename,
823
+ error: `map is ${(prepared.mapChars / 1048576).toFixed(1)} MB without sourcesContent; the ingester accepts up to 32 MB`
824
+ });
825
+ } else {
826
+ items.push(prepared);
827
+ }
828
+ }
829
+ if (options.dryRun) {
830
+ summary.uploaded = items.map(strip);
831
+ return summary;
832
+ }
833
+ const key = (options.key ?? env.AUTTER_RUNTIME_KEY ?? "").trim();
834
+ if (!key) throw new FatalUploadError("no ingest key: set AUTTER_RUNTIME_KEY to a server key (autter_rt_\u2026)");
835
+ if (key.startsWith("autter_rtc_")) {
836
+ throw new FatalUploadError("AUTTER_RUNTIME_KEY is a publishable client key (autter_rtc_\u2026); uploads need a server key (autter_rt_\u2026)");
837
+ }
838
+ const headers = { "content-type": "application/json", authorization: `Bearer ${key}` };
839
+ const uploadHeaders = { ...headers, "content-encoding": "gzip" };
840
+ const skipped = /* @__PURE__ */ new Set();
841
+ for (let start = 0; start < items.length && !summary.legacyIngester; start += CHECK_BATCH) {
842
+ const batch = items.slice(start, start + CHECK_BATCH);
843
+ try {
844
+ const res = await doFetch(`${endpoint}/v1/sourcemaps/check`, {
845
+ method: "POST",
846
+ headers,
847
+ body: JSON.stringify({
848
+ release,
849
+ files: batch.map((item) => ({ filename: item.filename, ...item.debugId ? { debugId: item.debugId } : {}, hash: item.hash }))
850
+ })
851
+ });
852
+ if (res.status === 404) {
853
+ summary.legacyIngester = true;
854
+ log(
855
+ "warning: this ingester predates 1.6.0, so it stores no debug ids and rejects .mjs/.cjs maps. Upgrade it: docker pull ghcr.io/autter-dev/otlp-ingester:latest"
856
+ );
857
+ break;
858
+ }
859
+ if (res.status === 401 || res.status === 403) {
860
+ throw new FatalUploadError(`the ingester rejected the key (${res.status}): ${(await res.text()).slice(0, 300)}`);
861
+ }
862
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
863
+ const body = await res.json();
864
+ const present = new Set(Array.isArray(body.present) ? body.present : []);
865
+ batch.forEach((item, index) => {
866
+ if (present.has(index)) skipped.add(item);
867
+ });
868
+ } catch (err) {
869
+ if (err instanceof FatalUploadError) throw err;
870
+ log(`warning: could not check which maps the ingester already has (${err.message}); uploading all`);
871
+ }
872
+ }
873
+ const uploaded = [];
874
+ let fatal = null;
875
+ const uploadOne = async (item) => {
876
+ for (let attempt = 1; ; attempt++) {
877
+ if (fatal) return;
878
+ let status = 0;
879
+ let detail = "";
880
+ try {
881
+ const res = await doFetch(`${endpoint}/v1/sourcemaps`, { method: "POST", headers: uploadHeaders, body: item.body });
882
+ status = res.status;
883
+ if (res.ok) {
884
+ uploaded.push(item);
885
+ return;
886
+ }
887
+ detail = (await res.text()).slice(0, 300);
888
+ } catch (err) {
889
+ detail = err.message;
890
+ }
891
+ if (status === 401 || status === 403) {
892
+ fatal = new FatalUploadError(`the ingester rejected the key (${status}): ${detail}`);
893
+ return;
894
+ }
895
+ const retryable = status === 0 || status === 429 || status >= 500;
896
+ if (!retryable || attempt >= MAX_ATTEMPTS) {
897
+ let error = status ? `HTTP ${status}: ${detail}` : detail;
898
+ if (status === 413 && item.bytes > LEGACY_MAX_BYTES) {
899
+ error += ` (this map is ${(item.bytes / 1048576).toFixed(1)} MB; ingester 1.6.0 and older accept up to 5 MB, newer ones 32 MB)`;
900
+ }
901
+ summary.failed.push({ path: item.path, filename: item.filename, error });
902
+ return;
903
+ }
904
+ await sleep(500 * 2 ** (attempt - 1));
905
+ }
906
+ };
907
+ const queue = items.filter((item) => !skipped.has(item));
908
+ const workers = Array.from({ length: Math.max(1, Math.min(options.concurrency ?? 8, queue.length)) }, async () => {
909
+ for (let item = queue.shift(); item; item = queue.shift()) await uploadOne(item);
910
+ });
911
+ await Promise.all(workers);
912
+ if (fatal) throw fatal;
913
+ const order = (a, b) => items.indexOf(a) - items.indexOf(b);
914
+ uploaded.sort(order);
915
+ if (options.deleteAfterUpload) {
916
+ for (const item of [...uploaded, ...skipped]) {
917
+ await (0, import_promises3.rm)(item.bundle.map, { force: true });
918
+ const code = await (0, import_promises3.readFile)(item.bundle.js, "utf8");
919
+ const stripped = stripSourceMappingUrl(code);
920
+ if (stripped !== code) await (0, import_promises3.writeFile)(item.bundle.js, stripped);
921
+ summary.deletedMaps.push(item.bundle.map);
922
+ }
923
+ }
924
+ summary.uploaded = uploaded.map(strip);
925
+ summary.skipped = [...skipped].sort(order).map(strip);
926
+ return summary;
927
+ }
928
+ function strip(item) {
929
+ const { path, filename, debugId, hash, bytes } = item;
930
+ return { path, filename, debugId, hash, bytes };
931
+ }
932
+
933
+ // src/build.ts
934
+ var import_node_fs2 = require("fs");
935
+ var import_node_path2 = require("path");
936
+ function buildKey(options) {
937
+ const key = (options.key ?? process.env.AUTTER_RUNTIME_KEY ?? "").trim();
938
+ return key || null;
939
+ }
940
+ function formatUploadSummary(summary) {
941
+ const lines = [];
942
+ const verb = summary.dryRun ? "would upload" : "uploaded";
943
+ for (const item of summary.uploaded) {
944
+ lines.push(`${verb} ${item.filename}${item.debugId ? ` (debug id ${item.debugId})` : ""}`);
945
+ }
946
+ for (const item of summary.skipped) lines.push(`skipped ${item.filename} (already uploaded)`);
947
+ for (const item of summary.failed) lines.push(`failed ${item.filename}: ${item.error}`);
948
+ lines.push(
949
+ `${summary.uploaded.length} ${verb}, ${summary.skipped.length} already uploaded, ${summary.failed.length} failed (release ${summary.release} from ${summary.releaseSource}, ${summary.endpoint})`
950
+ );
951
+ return lines;
952
+ }
953
+ async function processBuildOutput(input) {
954
+ const { options } = input;
955
+ const log = (line) => {
956
+ if (!options.silent) console.log(`[autter-runtime] ${line}`);
957
+ };
958
+ const result = { injected: [], upload: null, removedMaps: [] };
959
+ let outcome = "they were uploaded";
960
+ const owners = /* @__PURE__ */ new Map();
961
+ if (input.ownMaps) {
962
+ for (const bundle of await findBundles(input.dir, input.files)) owners.set(bundle.map, bundle.js);
963
+ }
964
+ try {
965
+ try {
966
+ result.injected = await injectDir(input.dir, {
967
+ files: input.files,
968
+ dryRun: options.dryRun,
969
+ stripSourceMappingUrl: input.stripSourceMappingUrl
970
+ });
971
+ const changed = result.injected.filter((r) => r.status === "injected").length;
972
+ if (result.injected.length) {
973
+ log(`debug ids: ${changed} bundle(s) injected, ${result.injected.length - changed} already had one`);
974
+ }
975
+ for (const bad of result.injected.filter((r) => r.status === "invalid-map")) log(`skipped ${bad.path}: its map is not valid JSON`);
976
+ if (options.upload === false) return result;
977
+ const key = buildKey(options);
978
+ if (!key && !options.dryRun) {
979
+ outcome = "AUTTER_RUNTIME_KEY is not set";
980
+ if (result.injected.length && !input.ownMaps) log("AUTTER_RUNTIME_KEY is not set: source maps were not uploaded");
981
+ return result;
982
+ }
983
+ if (!result.injected.some((r) => r.status !== "invalid-map")) {
984
+ outcome = "no bundle had a usable map to upload";
985
+ return result;
986
+ }
987
+ result.upload = await uploadDir(input.dir, {
988
+ files: input.files,
989
+ release: options.release,
990
+ urlPrefix: options.urlPrefix ?? input.urlPrefix,
991
+ endpoint: options.endpoint,
992
+ key: key ?? void 0,
993
+ dryRun: options.dryRun,
994
+ concurrency: options.concurrency,
995
+ deleteAfterUpload: options.deleteAfterUpload ?? input.deleteAfterUpload,
996
+ log
997
+ });
998
+ for (const line of formatUploadSummary(result.upload)) log(line);
999
+ const { failed, uploaded, skipped, dryRun } = result.upload;
1000
+ if (dryRun) outcome = "dry run, nothing was uploaded";
1001
+ else if (failed.length) {
1002
+ outcome = `${failed.length} of ${failed.length + uploaded.length + skipped.length} could not be uploaded (${failed[0].error})`;
1003
+ }
1004
+ if (failed.length && options.failOnError) {
1005
+ throw new Error(`${failed.length} source map upload(s) failed`);
1006
+ }
1007
+ } catch (err) {
1008
+ const message = err instanceof Error ? err.message : String(err);
1009
+ if (outcome === "they were uploaded") outcome = `the upload failed (${message})`;
1010
+ if (options.failOnError) throw new Error(`[autter-runtime] source maps: ${message}`);
1011
+ if (!options.silent) console.warn(`[autter-runtime] source maps: ${message}`);
1012
+ }
1013
+ } finally {
1014
+ await cleanUp();
1015
+ }
1016
+ return result;
1017
+ async function cleanUp() {
1018
+ if (!input.ownMaps) return;
1019
+ const maps = /* @__PURE__ */ new Set([...input.maps ?? [], ...owners.keys()]);
1020
+ const rel = (path) => (0, import_node_path2.relative)(input.dir, path).split(import_node_path2.sep).join("/");
1021
+ if (options.upload === false || options.deleteAfterUpload === false) {
1022
+ const kept = [...maps].filter((map) => (0, import_node_fs2.existsSync)(map));
1023
+ if (kept.length) {
1024
+ log(
1025
+ `kept ${kept.length} source map(s) this plugin generated (${options.upload === false ? "upload: false" : "deleteAfterUpload: false"}): they expose your source, so upload them with \`autter-runtime sourcemaps upload --delete-after-upload\` or keep them out of the deploy`
1026
+ );
1027
+ }
1028
+ return;
1029
+ }
1030
+ try {
1031
+ await removeSourceMaps(maps, owners);
1032
+ } catch (err) {
1033
+ const message = `could not delete the source maps this plugin generated (${err instanceof Error ? err.message : String(err)}): keep them out of the deploy`;
1034
+ if (options.failOnError) throw new Error(`[autter-runtime] ${message}`);
1035
+ if (!options.silent) console.warn(`[autter-runtime] ${message}`);
1036
+ }
1037
+ result.removedMaps = [...maps].filter((map) => !(0, import_node_fs2.existsSync)(map)).map(rel).sort();
1038
+ if (result.removedMaps.length) {
1039
+ log(`removed ${result.removedMaps.length} source map(s) this plugin generated, so they are not deployed: ${outcome}`);
1040
+ }
1041
+ }
1042
+ }
1043
+ // Annotate the CommonJS export names for ESM import in node:
1044
+ 0 && (module.exports = {
1045
+ BUNDLE_RE,
1046
+ DEBUG_ID_RE,
1047
+ DEBUG_ID_REGISTRY,
1048
+ DEFAULT_ENDPOINT,
1049
+ FatalUploadError,
1050
+ MAX_MAP_CHARS,
1051
+ MAX_UPLOAD_BYTES,
1052
+ RELEASE_ENV_VARS,
1053
+ RELEASE_RE,
1054
+ SCOPES_KEY,
1055
+ SCOPES_VERSION,
1056
+ SNIPPET_LINE_KEY,
1057
+ computeScopes,
1058
+ debugIdFor,
1059
+ debugIdSnippet,
1060
+ findBundles,
1061
+ formatUploadSummary,
1062
+ gitHead,
1063
+ hasDebugIdSnippet,
1064
+ injectBundle,
1065
+ injectDir,
1066
+ mapPathFor,
1067
+ normalizeDebugId,
1068
+ processBuildOutput,
1069
+ readDebugIdComment,
1070
+ readSourceMappingUrl,
1071
+ resolveEndpoint,
1072
+ resolveRelease,
1073
+ servedFilename,
1074
+ shiftMappings,
1075
+ snippetLine,
1076
+ storedMapJson,
1077
+ stripSourceMappingUrl,
1078
+ uploadDir
1079
+ });