@autter/runtime-cli 1.0.0 → 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/vite.cjs CHANGED
@@ -24,40 +24,11 @@ __export(vite_exports, {
24
24
  default: () => vite_default
25
25
  });
26
26
  module.exports = __toCommonJS(vite_exports);
27
- var import_node_path2 = require("path");
28
-
29
- // src/inject.ts
30
- var import_promises2 = require("fs/promises");
27
+ var import_node_path3 = require("path");
31
28
 
32
- // src/debug-id.ts
33
- var import_node_crypto = require("crypto");
34
- var DEBUG_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
35
- function normalizeDebugId(value) {
36
- if (typeof value !== "string") return null;
37
- const id = value.trim().toLowerCase();
38
- return DEBUG_ID_RE.test(id) ? id : null;
39
- }
40
- function debugIdFor(bytes) {
41
- const hash = (0, import_node_crypto.createHash)("sha256").update(bytes).digest();
42
- hash[6] = hash[6] & 15 | 64;
43
- hash[8] = hash[8] & 63 | 128;
44
- const hex = hash.subarray(0, 16).toString("hex");
45
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
46
- }
47
- var DEBUG_ID_COMMENT_RE = /^\/\/# debugId=([0-9a-fA-F-]{36})[ \t]*\r?$/gm;
48
- function readDebugIdComment(code) {
49
- let found = null;
50
- for (const match of code.matchAll(DEBUG_ID_COMMENT_RE)) found = normalizeDebugId(match[1]) ?? found;
51
- return found;
52
- }
53
- var DEBUG_ID_REGISTRY = "_autterDebugIds";
54
- function debugIdSnippet(id) {
55
- 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){}}();`;
56
- }
57
- var SNIPPET_RE = /\(g\._autterDebugIds=g\._autterDebugIds\|\|\{\}\)\[s\]="[0-9a-f]{8}-/;
58
- function hasDebugIdSnippet(code) {
59
- return SNIPPET_RE.test(code);
60
- }
29
+ // src/build.ts
30
+ var import_node_fs2 = require("fs");
31
+ var import_node_path2 = require("path");
61
32
 
62
33
  // src/files.ts
63
34
  var import_node_fs = require("fs");
@@ -97,7 +68,7 @@ function mapPathFor(js, code) {
97
68
  const sibling = `${js}.map`;
98
69
  return (0, import_node_fs.existsSync)(sibling) ? sibling : null;
99
70
  }
100
- async function walk(dir, out) {
71
+ async function walk(dir, out, pattern = BUNDLE_RE) {
101
72
  let entries;
102
73
  try {
103
74
  entries = await (0, import_promises.readdir)(dir, { withFileTypes: true });
@@ -107,9 +78,46 @@ async function walk(dir, out) {
107
78
  for (const entry of entries) {
108
79
  if (entry.name === "node_modules") continue;
109
80
  const full = (0, import_node_path.join)(dir, entry.name);
110
- if (entry.isDirectory()) await walk(full, out);
111
- else if (entry.isFile() && BUNDLE_RE.test(entry.name)) out.push(full);
81
+ if (entry.isDirectory()) await walk(full, out, pattern);
82
+ else if (entry.isFile() && pattern.test(entry.name)) out.push(full);
83
+ }
84
+ }
85
+ var CSS_SOURCE_MAPPING_URL_RE = /\/\*[#@] sourceMappingURL=([^\s*]+)\s*\*\/\s*$/;
86
+ function pointsAt(file, url, map) {
87
+ if (!url || /^[a-z][\w+.-]*:/i.test(url) || url.startsWith("/")) return false;
88
+ let path = url.split(/[?#]/)[0];
89
+ try {
90
+ path = decodeURIComponent(path);
91
+ } catch {
112
92
  }
93
+ return (0, import_node_path.resolve)((0, import_node_path.dirname)(file), path) === map;
94
+ }
95
+ async function stripReference(file, map) {
96
+ let code;
97
+ try {
98
+ code = await (0, import_promises.readFile)(file, "utf8");
99
+ } catch {
100
+ return;
101
+ }
102
+ let stripped = code;
103
+ if (BUNDLE_RE.test(file)) {
104
+ if (pointsAt(file, readSourceMappingUrl(code), map)) stripped = stripSourceMappingUrl(code);
105
+ } else if (file.endsWith(".css")) {
106
+ const match = CSS_SOURCE_MAPPING_URL_RE.exec(code);
107
+ if (match && pointsAt(file, match[1], map)) stripped = code.slice(0, match.index).replace(/\n?$/, "\n");
108
+ }
109
+ if (stripped !== code) await (0, import_promises.writeFile)(file, stripped);
110
+ }
111
+ async function removeSourceMaps(maps, owners = /* @__PURE__ */ new Map()) {
112
+ const removed = [];
113
+ for (const map of [...new Set(maps)].sort()) {
114
+ if (!(0, import_node_fs.existsSync)(map)) continue;
115
+ await (0, import_promises.rm)(map, { force: true });
116
+ removed.push(map);
117
+ const owner = owners.get(map) ?? map.replace(/\.map$/, "");
118
+ await stripReference(owner, map);
119
+ }
120
+ return removed;
113
121
  }
114
122
  async function findBundles(dir, files) {
115
123
  const root = (0, import_node_path.resolve)(dir);
@@ -133,6 +141,39 @@ async function findBundles(dir, files) {
133
141
  return bundles;
134
142
  }
135
143
 
144
+ // src/inject.ts
145
+ var import_promises2 = require("fs/promises");
146
+
147
+ // src/debug-id.ts
148
+ var import_node_crypto = require("crypto");
149
+ var DEBUG_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
150
+ function normalizeDebugId(value) {
151
+ if (typeof value !== "string") return null;
152
+ const id = value.trim().toLowerCase();
153
+ return DEBUG_ID_RE.test(id) ? id : null;
154
+ }
155
+ function debugIdFor(bytes) {
156
+ const hash = (0, import_node_crypto.createHash)("sha256").update(bytes).digest();
157
+ hash[6] = hash[6] & 15 | 64;
158
+ hash[8] = hash[8] & 63 | 128;
159
+ const hex = hash.subarray(0, 16).toString("hex");
160
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
161
+ }
162
+ var DEBUG_ID_COMMENT_RE = /^\/\/# debugId=([0-9a-fA-F-]{36})[ \t]*\r?$/gm;
163
+ function readDebugIdComment(code) {
164
+ let found = null;
165
+ for (const match of code.matchAll(DEBUG_ID_COMMENT_RE)) found = normalizeDebugId(match[1]) ?? found;
166
+ return found;
167
+ }
168
+ var DEBUG_ID_REGISTRY = "_autterDebugIds";
169
+ function debugIdSnippet(id) {
170
+ 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){}}();`;
171
+ }
172
+ var SNIPPET_RE = /\(g\._autterDebugIds=g\._autterDebugIds\|\|\{\}\)\[s\]="[0-9a-f]{8}-/;
173
+ function hasDebugIdSnippet(code) {
174
+ return SNIPPET_RE.test(code);
175
+ }
176
+
136
177
  // src/inject.ts
137
178
  var SNIPPET_LINE_KEY = "x_autter_snippet_line";
138
179
  function snippetLine(code) {
@@ -235,6 +276,8 @@ async function injectDir(dir, options = {}) {
235
276
  // src/upload.ts
236
277
  var import_node_crypto2 = require("crypto");
237
278
  var import_promises3 = require("fs/promises");
279
+ var import_node_util = require("util");
280
+ var import_node_zlib = require("zlib");
238
281
 
239
282
  // src/release.ts
240
283
  var import_node_child_process = require("child_process");
@@ -280,9 +323,382 @@ function resolveRelease(explicit, env = process.env, cwd = process.cwd()) {
280
323
  );
281
324
  }
282
325
 
326
+ // src/scopes.ts
327
+ var import_acorn = require("acorn");
328
+ var SCOPES_KEY = "x_autter_scopes";
329
+ var SCOPES_VERSION = 1;
330
+ var BASE_OPTIONS = {
331
+ ecmaVersion: "latest",
332
+ allowHashBang: true,
333
+ allowReturnOutsideFunction: true,
334
+ allowReserved: true
335
+ };
336
+ function parseBundle(code) {
337
+ try {
338
+ return (0, import_acorn.parse)(code, {
339
+ ...BASE_OPTIONS,
340
+ sourceType: "module",
341
+ allowAwaitOutsideFunction: true,
342
+ allowImportExportEverywhere: true
343
+ });
344
+ } catch (moduleError) {
345
+ try {
346
+ return (0, import_acorn.parse)(code, { ...BASE_OPTIONS, sourceType: "script" });
347
+ } catch (scriptError) {
348
+ const pos = (err) => typeof err.pos === "number" ? err.pos : -1;
349
+ throw pos(scriptError) > pos(moduleError) ? scriptError : moduleError;
350
+ }
351
+ }
352
+ }
353
+ function isNode(value) {
354
+ return typeof value === "object" && value !== null && typeof value.type === "string";
355
+ }
356
+ var IDENTIFIER_NAME_RE = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
357
+ function identifierToken(node) {
358
+ if (!isNode(node)) return null;
359
+ if (node.type === "Identifier") return { offset: node.start, name: node.name, literal: false };
360
+ if (node.type === "PrivateIdentifier") return { offset: node.start, name: `#${node.name}`, literal: false };
361
+ return null;
362
+ }
363
+ function literalToken(node) {
364
+ if (!isNode(node) || node.type !== "Literal" || typeof node.value !== "string") return null;
365
+ return IDENTIFIER_NAME_RE.test(node.value) ? { offset: node.start, name: node.value, literal: true } : null;
366
+ }
367
+ function keyToken(property) {
368
+ if (!property.computed) {
369
+ const id = identifierToken(property.key);
370
+ if (id) return id;
371
+ }
372
+ return literalToken(property.key);
373
+ }
374
+ function bindingToken(target) {
375
+ if (!isNode(target)) return null;
376
+ if (target.type === "Identifier") return identifierToken(target);
377
+ if (target.type === "MemberExpression") {
378
+ return target.computed ? literalToken(target.property) : identifierToken(target.property);
379
+ }
380
+ return null;
381
+ }
382
+ function contextTokens(node, parent) {
383
+ let token = null;
384
+ switch (parent?.type) {
385
+ case "VariableDeclarator":
386
+ if (parent.init === node) token = bindingToken(parent.id);
387
+ break;
388
+ case "AssignmentExpression":
389
+ case "AssignmentPattern":
390
+ if (parent.right === node) token = bindingToken(parent.left);
391
+ break;
392
+ case "Property":
393
+ case "PropertyDefinition":
394
+ case "MethodDefinition":
395
+ if (parent.value === node) token = keyToken(parent);
396
+ break;
397
+ }
398
+ return token ? [token] : [];
399
+ }
400
+ function classTokens(path) {
401
+ if (!path || path.node.type !== "ClassDeclaration" && path.node.type !== "ClassExpression") return [];
402
+ const own = identifierToken(path.node.id);
403
+ return [...own ? [own] : [], ...contextTokens(path.node, path.parent?.node)];
404
+ }
405
+ function describe(path) {
406
+ const fn = path.node;
407
+ const parent = path.parent?.node;
408
+ const own = identifierToken(fn.id);
409
+ const isMethod = parent?.type === "MethodDefinition" || parent?.type === "Property" && parent.value === fn && (parent.method === true || parent.kind !== "init");
410
+ let context;
411
+ if (parent?.type === "MethodDefinition" && parent.kind === "constructor") {
412
+ context = classTokens(path.parent?.parent?.parent ?? null);
413
+ } else {
414
+ context = contextTokens(fn, parent);
415
+ }
416
+ return {
417
+ start: fn.start,
418
+ end: fn.end,
419
+ own,
420
+ recoverAt: !own && fn.type !== "ArrowFunctionExpression" && !isMethod ? fn.start : null,
421
+ context
422
+ };
423
+ }
424
+ var FUNCTION_TYPES = /* @__PURE__ */ new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
425
+ function classInitializer(path) {
426
+ const node = path.node;
427
+ let range = null;
428
+ if (node.type === "StaticBlock") range = node;
429
+ else if (node.type === "PropertyDefinition" && isNode(node.value) && !FUNCTION_TYPES.has(node.value.type)) range = node.value;
430
+ if (!range) return null;
431
+ return { start: range.start, end: range.end, own: null, recoverAt: null, context: classTokens(path.parent?.parent ?? null) };
432
+ }
433
+ function collectFunctions(program) {
434
+ const found = [];
435
+ const stack = [{ node: program, parent: null }];
436
+ for (let path = stack.pop(); path; path = stack.pop()) {
437
+ const node = path.node;
438
+ if (FUNCTION_TYPES.has(node.type)) found.push(describe(path));
439
+ else {
440
+ const initializer = classInitializer(path);
441
+ if (initializer) found.push(initializer);
442
+ }
443
+ for (const key in node) {
444
+ const value = node[key];
445
+ if (Array.isArray(value)) {
446
+ for (let i = value.length - 1; i >= 0; i--) if (isNode(value[i])) stack.push({ node: value[i], parent: path });
447
+ } else if (isNode(value)) {
448
+ stack.push({ node: value, parent: path });
449
+ }
450
+ }
451
+ }
452
+ return found;
453
+ }
454
+ function lineStarts(code) {
455
+ const starts = [0];
456
+ for (let i = 0; i < code.length; i++) {
457
+ const c = code.charCodeAt(i);
458
+ if (c === 10 || c === 8232 || c === 8233) starts.push(i + 1);
459
+ else if (c === 13) {
460
+ if (code.charCodeAt(i + 1) === 10) i++;
461
+ starts.push(i + 1);
462
+ }
463
+ }
464
+ return starts;
465
+ }
466
+ function positionOf(starts, offset) {
467
+ let lo = 0;
468
+ let hi = starts.length - 1;
469
+ while (lo < hi) {
470
+ const mid = lo + hi + 1 >> 1;
471
+ if (starts[mid] <= offset) lo = mid;
472
+ else hi = mid - 1;
473
+ }
474
+ return [lo, offset - starts[lo]];
475
+ }
476
+ var BASE64 = new Int8Array(128).fill(-1);
477
+ for (const [i, ch] of [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].entries()) BASE64[ch.charCodeAt(0)] = i;
478
+ function findSegments(mappings, wanted) {
479
+ let line = 0;
480
+ let column = 0;
481
+ let source = 0;
482
+ let originalLine = 0;
483
+ let originalColumn = 0;
484
+ let name = 0;
485
+ let want = wanted.get(0);
486
+ const fields = [0, 0, 0, 0, 0];
487
+ let i = 0;
488
+ while (i < mappings.length) {
489
+ const ch = mappings.charCodeAt(i);
490
+ if (ch === 59) {
491
+ line++;
492
+ column = 0;
493
+ want = wanted.get(line);
494
+ i++;
495
+ continue;
496
+ }
497
+ if (ch === 44) {
498
+ i++;
499
+ continue;
500
+ }
501
+ let count = 0;
502
+ while (i < mappings.length) {
503
+ const next = mappings.charCodeAt(i);
504
+ if (next === 44 || next === 59) break;
505
+ let value = 0;
506
+ let shift = 0;
507
+ let digit;
508
+ do {
509
+ const code = mappings.charCodeAt(i++);
510
+ digit = code < 128 ? BASE64[code] : -1;
511
+ if (digit < 0 || shift > 30) throw new Error("invalid mappings");
512
+ value |= (digit & 31) << shift;
513
+ shift += 5;
514
+ } while (digit & 32);
515
+ const decoded = value & 1 ? -(value >>> 1) : value >>> 1;
516
+ if (count < 5) fields[count] = decoded;
517
+ count++;
518
+ }
519
+ column += fields[0];
520
+ if (count >= 4) {
521
+ source += fields[1];
522
+ originalLine += fields[2];
523
+ originalColumn += fields[3];
524
+ }
525
+ if (count >= 5) name += fields[4];
526
+ if (want && want.get(column) === null) {
527
+ want.set(column, {
528
+ source: count >= 4 ? source : -1,
529
+ line: originalLine,
530
+ column: originalColumn,
531
+ name: count >= 5 ? name : -1
532
+ });
533
+ }
534
+ }
535
+ }
536
+ function looksMangled(name) {
537
+ return name.replace(/^#/, "").length <= 2;
538
+ }
539
+ var IDENTIFIER_AT_RE = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/uy;
540
+ var OWN_NAME_AT_RE = /(?:async\s+)?function\b\s*\*?\s*([$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)/uy;
541
+ var NOT_A_NAME = new Set(
542
+ "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(" ")
543
+ );
544
+ var NameResolver = class {
545
+ constructor(map, segmentAt) {
546
+ this.segmentAt = segmentAt;
547
+ this.names = Array.isArray(map.names) ? map.names : [];
548
+ this.sourcesContent = Array.isArray(map.sourcesContent) ? map.sourcesContent : [];
549
+ }
550
+ segmentAt;
551
+ names;
552
+ sourcesContent;
553
+ sourceLines = /* @__PURE__ */ new Map();
554
+ originalLine(segment) {
555
+ if (segment.source < 0) return null;
556
+ let lines = this.sourceLines.get(segment.source);
557
+ if (lines === void 0) {
558
+ const content = this.sourcesContent[segment.source];
559
+ lines = typeof content === "string" ? content.split(/\r\n|[\n\r\u2028\u2029]/) : null;
560
+ this.sourceLines.set(segment.source, lines);
561
+ }
562
+ return lines?.[segment.line] ?? null;
563
+ }
564
+ /** The original identifier at a segment's source position. */
565
+ identifierAt(segment, re, group = 0) {
566
+ const text = this.originalLine(segment);
567
+ if (text === null) return null;
568
+ re.lastIndex = segment.column;
569
+ const found = re.exec(text)?.[group];
570
+ return found && !NOT_A_NAME.has(found) ? found : null;
571
+ }
572
+ /** Original name of a token: the map's `names` at its exact position;
573
+ * else the generated name when it isn't mangled; else the identifier
574
+ * at the mapped position in `sourcesContent`. Null when unknown. */
575
+ resolve(token) {
576
+ if (token.literal) return token.name;
577
+ const segment = this.segmentAt(token.offset);
578
+ if (segment && segment.name >= 0) {
579
+ const name = this.names[segment.name];
580
+ if (typeof name === "string" && name) return name;
581
+ }
582
+ if (!looksMangled(token.name)) return token.name;
583
+ return segment ? this.identifierAt(segment, IDENTIFIER_AT_RE) : null;
584
+ }
585
+ /** The name a minifier removed from `function name() {}`, read from the
586
+ * original source at the function's mapped start. */
587
+ recover(offset) {
588
+ const segment = this.segmentAt(offset);
589
+ return segment ? this.identifierAt(segment, OWN_NAME_AT_RE, 1) : null;
590
+ }
591
+ };
592
+ var BASE64_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
593
+ function vlq(value) {
594
+ let rest = value < 0 ? -value << 1 | 1 : value << 1;
595
+ let out = "";
596
+ do {
597
+ let digit = rest & 31;
598
+ rest >>>= 5;
599
+ if (rest > 0) digit |= 32;
600
+ out += BASE64_DIGITS[digit];
601
+ } while (rest > 0);
602
+ return out;
603
+ }
604
+ function encodeScopes(entries) {
605
+ const parts = [];
606
+ let line = 0;
607
+ let previousStart = 0;
608
+ let previousName = 0;
609
+ let firstOnLine = true;
610
+ for (const [startLine, startColumn, endLine, endColumn, nameIndex] of entries) {
611
+ if (startLine > line) {
612
+ parts.push(";".repeat(startLine - line));
613
+ line = startLine;
614
+ previousStart = 0;
615
+ firstOnLine = true;
616
+ }
617
+ if (!firstOnLine) parts.push(",");
618
+ firstOnLine = false;
619
+ let segment = vlq(startColumn - previousStart) + vlq(endLine - startLine) + vlq(endLine === startLine ? endColumn - startColumn : endColumn);
620
+ previousStart = startColumn;
621
+ if (nameIndex >= 0) {
622
+ segment += vlq(nameIndex - previousName);
623
+ previousName = nameIndex;
624
+ }
625
+ parts.push(segment);
626
+ }
627
+ return parts.join("");
628
+ }
629
+ function computeScopes(code, map) {
630
+ try {
631
+ return scopesOf(code, map);
632
+ } catch (err) {
633
+ return { error: err instanceof Error ? err.message : String(err) };
634
+ }
635
+ }
636
+ function scopesOf(code, map) {
637
+ if (typeof map.mappings !== "string") return { error: "the map has no mappings string" };
638
+ let functions;
639
+ try {
640
+ functions = collectFunctions(parseBundle(code));
641
+ } catch (err) {
642
+ return { error: `could not parse the bundle: ${err instanceof Error ? err.message : String(err)}` };
643
+ }
644
+ const starts = lineStarts(code);
645
+ const wanted = /* @__PURE__ */ new Map();
646
+ const want = (offset) => {
647
+ const [line, column] = positionOf(starts, offset);
648
+ let columns = wanted.get(line);
649
+ if (!columns) wanted.set(line, columns = /* @__PURE__ */ new Map());
650
+ columns.set(column, null);
651
+ };
652
+ for (const fn of functions) {
653
+ if (fn.own && !fn.own.literal) want(fn.own.offset);
654
+ if (fn.recoverAt !== null) want(fn.recoverAt);
655
+ for (const token of fn.context) if (!token.literal) want(token.offset);
656
+ }
657
+ try {
658
+ findSegments(map.mappings, wanted);
659
+ } catch (err) {
660
+ return { error: `could not read the map: ${err instanceof Error ? err.message : String(err)}` };
661
+ }
662
+ const resolver = new NameResolver(map, (offset) => {
663
+ const [line, column] = positionOf(starts, offset);
664
+ return wanted.get(line)?.get(column) ?? null;
665
+ });
666
+ functions.sort((a, b) => a.start - b.start || b.end - a.end);
667
+ const mapNames = Array.isArray(map.names) ? map.names : [];
668
+ const nameIndex = /* @__PURE__ */ new Map();
669
+ mapNames.forEach((name, index) => {
670
+ if (typeof name === "string" && !nameIndex.has(name)) nameIndex.set(name, index);
671
+ });
672
+ const extraNames = [];
673
+ const indexOf = (name) => {
674
+ let index = nameIndex.get(name);
675
+ if (index === void 0) {
676
+ index = mapNames.length + extraNames.push(name) - 1;
677
+ nameIndex.set(name, index);
678
+ }
679
+ return index;
680
+ };
681
+ const entries = functions.map((fn) => {
682
+ let name = fn.own ? resolver.resolve(fn.own) : null;
683
+ if (name === null && fn.recoverAt !== null) name = resolver.recover(fn.recoverAt);
684
+ for (const token of fn.context) {
685
+ if (name !== null) break;
686
+ name = resolver.resolve(token);
687
+ }
688
+ const index = name !== null ? indexOf(name) : fn.own || fn.context.length > 0 ? indexOf(null) : -1;
689
+ const [startLine, startColumn] = positionOf(starts, fn.start);
690
+ const [endLine, endColumn] = positionOf(starts, fn.end);
691
+ return [startLine, startColumn, endLine, endColumn, index];
692
+ });
693
+ return { scopes: { version: SCOPES_VERSION, names: extraNames, scopes: encodeScopes(entries) } };
694
+ }
695
+
283
696
  // src/upload.ts
284
697
  var DEFAULT_ENDPOINT = "https://otlp.autter.dev";
285
- var MAX_UPLOAD_BYTES = 5 * 1024 * 1024;
698
+ var MAX_MAP_CHARS = 32 * 1024 * 1024;
699
+ var MAX_UPLOAD_BYTES = MAX_MAP_CHARS + 1024 * 1024;
700
+ var LEGACY_MAX_BYTES = 5 * 1024 * 1024;
701
+ var gzip = (0, import_node_util.promisify)(import_node_zlib.gzip);
286
702
  var CHECK_BATCH = 500;
287
703
  var MAX_ATTEMPTS = 3;
288
704
  function resolveEndpoint(flag, env = process.env) {
@@ -299,7 +715,16 @@ function storedMapJson(map) {
299
715
  const { sourcesContent: _omitted, ...safe } = map;
300
716
  return JSON.stringify(safe);
301
717
  }
302
- async function prepare(bundle, urlPrefix, release) {
718
+ function bytesOf(buffer) {
719
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
720
+ }
721
+ function fits(json, body) {
722
+ return json.length <= MAX_MAP_CHARS && Buffer.byteLength(body) <= MAX_UPLOAD_BYTES;
723
+ }
724
+ function uploadBody(release, filename, debugId, json) {
725
+ return `{"release":${JSON.stringify(release)},"filename":${JSON.stringify(filename)},${debugId ? `"debugId":${JSON.stringify(debugId)},` : ""}"map":${json}}`;
726
+ }
727
+ async function prepare(bundle, urlPrefix, release, log, compress) {
303
728
  let map;
304
729
  try {
305
730
  map = JSON.parse(await (0, import_promises3.readFile)(bundle.map, "utf8"));
@@ -311,17 +736,31 @@ async function prepare(bundle, urlPrefix, release) {
311
736
  }
312
737
  const code = await (0, import_promises3.readFile)(bundle.js, "utf8");
313
738
  const debugId = readDebugIdComment(code) ?? normalizeDebugId(map.debugId);
314
- const json = storedMapJson(map);
315
739
  const filename = servedFilename(urlPrefix, bundle.path);
316
- const body = `{"release":${JSON.stringify(release)},"filename":${JSON.stringify(filename)},${debugId ? `"debugId":${JSON.stringify(debugId)},` : ""}"map":${json}}`;
740
+ const { [SCOPES_KEY]: _stale, ...plain } = map;
741
+ const scopes = computeScopes(code, map);
742
+ let json = storedMapJson(plain);
743
+ if ("scopes" in scopes) {
744
+ const scoped = storedMapJson({ ...plain, [SCOPES_KEY]: scopes.scopes });
745
+ if (fits(scoped, uploadBody(release, filename, debugId, scoped))) json = scoped;
746
+ else if (fits(json, uploadBody(release, filename, debugId, json))) {
747
+ log(`warning: ${bundle.path}: its map is over 32 MB with function scopes, so it is uploaded without them (frames keep call-site names)`);
748
+ }
749
+ } else {
750
+ log(`warning: ${bundle.path}: no function scopes (${scopes.error}); its map is uploaded without them (frames keep call-site names)`);
751
+ }
752
+ const body = uploadBody(release, filename, debugId, json);
317
753
  return {
318
754
  bundle,
319
- body,
755
+ // Maps are text that compresses several times over; the ingester
756
+ // inflates the body (Content-Encoding: gzip).
757
+ body: compress && fits(json, body) ? bytesOf(await gzip(body)) : new Uint8Array(0),
320
758
  path: bundle.path,
321
759
  filename,
322
760
  debugId,
323
761
  hash: (0, import_node_crypto2.createHash)("sha256").update(json).digest("hex"),
324
- bytes: Buffer.byteLength(body)
762
+ bytes: Buffer.byteLength(body),
763
+ mapChars: json.length
325
764
  };
326
765
  }
327
766
  var FatalUploadError = class extends Error {
@@ -349,14 +788,14 @@ async function uploadDir(dir, options = {}) {
349
788
  };
350
789
  const items = [];
351
790
  for (const bundle of await findBundles(dir, options.files)) {
352
- const prepared = await prepare(bundle, options.urlPrefix, release);
791
+ const prepared = await prepare(bundle, options.urlPrefix, release, log, !options.dryRun);
353
792
  if ("error" in prepared) {
354
793
  summary.failed.push({ path: bundle.path, filename: servedFilename(options.urlPrefix, bundle.path), error: prepared.error });
355
- } else if (prepared.bytes > MAX_UPLOAD_BYTES) {
794
+ } else if (prepared.mapChars > MAX_MAP_CHARS || prepared.bytes > MAX_UPLOAD_BYTES) {
356
795
  summary.failed.push({
357
796
  path: prepared.path,
358
797
  filename: prepared.filename,
359
- error: `map is ${(prepared.bytes / 1048576).toFixed(1)} MB without sourcesContent; the ingester accepts up to 5 MB`
798
+ error: `map is ${(prepared.mapChars / 1048576).toFixed(1)} MB without sourcesContent; the ingester accepts up to 32 MB`
360
799
  });
361
800
  } else {
362
801
  items.push(prepared);
@@ -372,6 +811,7 @@ async function uploadDir(dir, options = {}) {
372
811
  throw new FatalUploadError("AUTTER_RUNTIME_KEY is a publishable client key (autter_rtc_\u2026); uploads need a server key (autter_rt_\u2026)");
373
812
  }
374
813
  const headers = { "content-type": "application/json", authorization: `Bearer ${key}` };
814
+ const uploadHeaders = { ...headers, "content-encoding": "gzip" };
375
815
  const skipped = /* @__PURE__ */ new Set();
376
816
  for (let start = 0; start < items.length && !summary.legacyIngester; start += CHECK_BATCH) {
377
817
  const batch = items.slice(start, start + CHECK_BATCH);
@@ -413,7 +853,7 @@ async function uploadDir(dir, options = {}) {
413
853
  let status = 0;
414
854
  let detail = "";
415
855
  try {
416
- const res = await doFetch(`${endpoint}/v1/sourcemaps`, { method: "POST", headers, body: item.body });
856
+ const res = await doFetch(`${endpoint}/v1/sourcemaps`, { method: "POST", headers: uploadHeaders, body: item.body });
417
857
  status = res.status;
418
858
  if (res.ok) {
419
859
  uploaded.push(item);
@@ -429,7 +869,11 @@ async function uploadDir(dir, options = {}) {
429
869
  }
430
870
  const retryable = status === 0 || status === 429 || status >= 500;
431
871
  if (!retryable || attempt >= MAX_ATTEMPTS) {
432
- summary.failed.push({ path: item.path, filename: item.filename, error: status ? `HTTP ${status}: ${detail}` : detail });
872
+ let error = status ? `HTTP ${status}: ${detail}` : detail;
873
+ if (status === 413 && item.bytes > LEGACY_MAX_BYTES) {
874
+ 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)`;
875
+ }
876
+ summary.failed.push({ path: item.path, filename: item.filename, error });
433
877
  return;
434
878
  }
435
879
  await sleep(500 * 2 ** (attempt - 1));
@@ -462,6 +906,18 @@ function strip(item) {
462
906
  }
463
907
 
464
908
  // src/build.ts
909
+ function buildKey(options) {
910
+ const key = (options.key ?? process.env.AUTTER_RUNTIME_KEY ?? "").trim();
911
+ return key || null;
912
+ }
913
+ function shouldGenerateMaps(options) {
914
+ return options.upload === false || Boolean(options.dryRun) || buildKey(options) !== null;
915
+ }
916
+ function logMapsNotGenerated(options) {
917
+ if (!options.silent) {
918
+ console.log("[autter-runtime] AUTTER_RUNTIME_KEY is not set: no source maps generated, nothing uploaded");
919
+ }
920
+ }
465
921
  function formatUploadSummary(summary) {
466
922
  const lines = [];
467
923
  const verb = summary.dryRun ? "would upload" : "uploaded";
@@ -480,46 +936,90 @@ async function processBuildOutput(input) {
480
936
  const log = (line) => {
481
937
  if (!options.silent) console.log(`[autter-runtime] ${line}`);
482
938
  };
483
- const result = { injected: [], upload: null };
939
+ const result = { injected: [], upload: null, removedMaps: [] };
940
+ let outcome = "they were uploaded";
941
+ const owners = /* @__PURE__ */ new Map();
942
+ if (input.ownMaps) {
943
+ for (const bundle of await findBundles(input.dir, input.files)) owners.set(bundle.map, bundle.js);
944
+ }
484
945
  try {
485
- result.injected = await injectDir(input.dir, {
486
- files: input.files,
487
- dryRun: options.dryRun,
488
- stripSourceMappingUrl: input.stripSourceMappingUrl
489
- });
490
- const changed = result.injected.filter((r) => r.status === "injected").length;
491
- if (result.injected.length) {
492
- log(`debug ids: ${changed} bundle(s) injected, ${result.injected.length - changed} already had one`);
946
+ try {
947
+ result.injected = await injectDir(input.dir, {
948
+ files: input.files,
949
+ dryRun: options.dryRun,
950
+ stripSourceMappingUrl: input.stripSourceMappingUrl
951
+ });
952
+ const changed = result.injected.filter((r) => r.status === "injected").length;
953
+ if (result.injected.length) {
954
+ log(`debug ids: ${changed} bundle(s) injected, ${result.injected.length - changed} already had one`);
955
+ }
956
+ for (const bad of result.injected.filter((r) => r.status === "invalid-map")) log(`skipped ${bad.path}: its map is not valid JSON`);
957
+ if (options.upload === false) return result;
958
+ const key = buildKey(options);
959
+ if (!key && !options.dryRun) {
960
+ outcome = "AUTTER_RUNTIME_KEY is not set";
961
+ if (result.injected.length && !input.ownMaps) log("AUTTER_RUNTIME_KEY is not set: source maps were not uploaded");
962
+ return result;
963
+ }
964
+ if (!result.injected.some((r) => r.status !== "invalid-map")) {
965
+ outcome = "no bundle had a usable map to upload";
966
+ return result;
967
+ }
968
+ result.upload = await uploadDir(input.dir, {
969
+ files: input.files,
970
+ release: options.release,
971
+ urlPrefix: options.urlPrefix ?? input.urlPrefix,
972
+ endpoint: options.endpoint,
973
+ key: key ?? void 0,
974
+ dryRun: options.dryRun,
975
+ concurrency: options.concurrency,
976
+ deleteAfterUpload: options.deleteAfterUpload ?? input.deleteAfterUpload,
977
+ log
978
+ });
979
+ for (const line of formatUploadSummary(result.upload)) log(line);
980
+ const { failed, uploaded, skipped, dryRun } = result.upload;
981
+ if (dryRun) outcome = "dry run, nothing was uploaded";
982
+ else if (failed.length) {
983
+ outcome = `${failed.length} of ${failed.length + uploaded.length + skipped.length} could not be uploaded (${failed[0].error})`;
984
+ }
985
+ if (failed.length && options.failOnError) {
986
+ throw new Error(`${failed.length} source map upload(s) failed`);
987
+ }
988
+ } catch (err) {
989
+ const message = err instanceof Error ? err.message : String(err);
990
+ if (outcome === "they were uploaded") outcome = `the upload failed (${message})`;
991
+ if (options.failOnError) throw new Error(`[autter-runtime] source maps: ${message}`);
992
+ if (!options.silent) console.warn(`[autter-runtime] source maps: ${message}`);
493
993
  }
494
- for (const bad of result.injected.filter((r) => r.status === "invalid-map")) log(`skipped ${bad.path}: its map is not valid JSON`);
495
- if (options.upload === false) return result;
496
- const key = options.key ?? process.env.AUTTER_RUNTIME_KEY;
497
- if (!key && !options.dryRun) {
498
- if (result.injected.length) log("AUTTER_RUNTIME_KEY is not set: source maps were not uploaded");
499
- return result;
994
+ } finally {
995
+ await cleanUp();
996
+ }
997
+ return result;
998
+ async function cleanUp() {
999
+ if (!input.ownMaps) return;
1000
+ const maps = /* @__PURE__ */ new Set([...input.maps ?? [], ...owners.keys()]);
1001
+ const rel = (path) => (0, import_node_path2.relative)(input.dir, path).split(import_node_path2.sep).join("/");
1002
+ if (options.upload === false || options.deleteAfterUpload === false) {
1003
+ const kept = [...maps].filter((map) => (0, import_node_fs2.existsSync)(map));
1004
+ if (kept.length) {
1005
+ log(
1006
+ `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`
1007
+ );
1008
+ }
1009
+ return;
500
1010
  }
501
- if (!result.injected.some((r) => r.status !== "invalid-map")) return result;
502
- result.upload = await uploadDir(input.dir, {
503
- files: input.files,
504
- release: options.release,
505
- urlPrefix: options.urlPrefix ?? input.urlPrefix,
506
- endpoint: options.endpoint,
507
- key,
508
- dryRun: options.dryRun,
509
- concurrency: options.concurrency,
510
- deleteAfterUpload: options.deleteAfterUpload ?? input.deleteAfterUpload,
511
- log
512
- });
513
- for (const line of formatUploadSummary(result.upload)) log(line);
514
- if (result.upload.failed.length && options.failOnError) {
515
- throw new Error(`${result.upload.failed.length} source map upload(s) failed`);
1011
+ try {
1012
+ await removeSourceMaps(maps, owners);
1013
+ } catch (err) {
1014
+ const message = `could not delete the source maps this plugin generated (${err instanceof Error ? err.message : String(err)}): keep them out of the deploy`;
1015
+ if (options.failOnError) throw new Error(`[autter-runtime] ${message}`);
1016
+ if (!options.silent) console.warn(`[autter-runtime] ${message}`);
1017
+ }
1018
+ result.removedMaps = [...maps].filter((map) => !(0, import_node_fs2.existsSync)(map)).map(rel).sort();
1019
+ if (result.removedMaps.length) {
1020
+ log(`removed ${result.removedMaps.length} source map(s) this plugin generated, so they are not deployed: ${outcome}`);
516
1021
  }
517
- } catch (err) {
518
- const message = `source maps: ${err instanceof Error ? err.message : String(err)}`;
519
- if (options.failOnError) throw new Error(`[autter-runtime] ${message}`);
520
- if (!options.silent) console.warn(`[autter-runtime] ${message}`);
521
1022
  }
522
- return result;
523
1023
  }
524
1024
 
525
1025
  // src/vite.ts
@@ -535,7 +1035,11 @@ function autterSourceMaps(options = {}) {
535
1035
  config(config) {
536
1036
  isVite = true;
537
1037
  const current = config.build?.sourcemap;
538
- if (current === void 0 || current === false) {
1038
+ if ((current === void 0 || current === false) && !config.build?.ssr) {
1039
+ if (!shouldGenerateMaps(options)) {
1040
+ logMapsNotGenerated(options);
1041
+ return void 0;
1042
+ }
539
1043
  enabledMaps = true;
540
1044
  return { build: { sourcemap: "hidden" } };
541
1045
  }
@@ -550,21 +1054,40 @@ function autterSourceMaps(options = {}) {
550
1054
  },
551
1055
  outputOptions(output) {
552
1056
  if (isVite || output.sourcemap !== void 0 && output.sourcemap !== false) return null;
1057
+ if (!shouldGenerateMaps(options)) {
1058
+ logMapsNotGenerated(options);
1059
+ return null;
1060
+ }
553
1061
  enabledMaps = true;
554
1062
  return { ...output, sourcemap: "hidden" };
555
1063
  },
556
1064
  async writeBundle(output, bundle) {
557
- const environment = this?.environment;
558
- if (ssr || environment?.config?.consumer === "server") return;
559
- const dir = output.dir ?? (output.file ? (0, import_node_path2.dirname)(output.file) : void 0);
1065
+ const dir = output.dir ?? (output.file ? (0, import_node_path3.dirname)(output.file) : void 0);
560
1066
  if (!dir) return;
561
- const files = Object.values(bundle).filter((file) => file.type === "chunk").map((file) => (0, import_node_path2.resolve)(dir, file.fileName));
1067
+ const maps = Object.values(bundle).filter((file) => file.fileName.endsWith(".map")).map((file) => (0, import_node_path3.resolve)(dir, file.fileName));
1068
+ const environment = this?.environment;
1069
+ if (ssr || environment?.config?.consumer === "server") {
1070
+ if (enabledMaps && options.deleteAfterUpload !== false) {
1071
+ try {
1072
+ const removed = await removeSourceMaps(maps);
1073
+ if (removed.length && !options.silent) {
1074
+ console.log(`[autter-runtime] removed ${removed.length} source map(s) this plugin generated for a server bundle (not uploaded)`);
1075
+ }
1076
+ } catch (err) {
1077
+ if (!options.silent) console.warn(`[autter-runtime] could not delete server source maps: ${err instanceof Error ? err.message : String(err)}`);
1078
+ }
1079
+ }
1080
+ return;
1081
+ }
1082
+ const files = Object.values(bundle).filter((file) => file.type === "chunk").map((file) => (0, import_node_path3.resolve)(dir, file.fileName));
562
1083
  await processBuildOutput({
563
1084
  dir,
564
1085
  files,
1086
+ maps,
565
1087
  urlPrefix: base,
566
1088
  options,
567
- deleteAfterUpload: enabledMaps
1089
+ deleteAfterUpload: enabledMaps,
1090
+ ownMaps: enabledMaps
568
1091
  });
569
1092
  }
570
1093
  };