@awsless/cli 0.1.29 → 0.1.30

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.
@@ -1,3 +1,6 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
1
4
  // src/feature/on-error-log/server/handle.ts
2
5
  import { createHash } from "crypto";
3
6
  import * as zlib from "zlib";
@@ -16,6 +19,640 @@ import {
16
19
  transform,
17
20
  uuid
18
21
  } from "@awsless/validate";
22
+
23
+ // src/feature/on-error-log/keys.ts
24
+ var SOURCEMAP_ROOT = "sourcemaps/";
25
+ var formatSourcemapVersionKey = (name, version) => {
26
+ return `${SOURCEMAP_ROOT}${name}/versions/${version}`;
27
+ };
28
+
29
+ // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
30
+ var comma = 44;
31
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
32
+ var intToChar = new Uint8Array(64);
33
+ var charToInt = new Uint8Array(128);
34
+ for (let i = 0;i < chars.length; i++) {
35
+ const c = chars.charCodeAt(i);
36
+ intToChar[i] = c;
37
+ charToInt[c] = i;
38
+ }
39
+ function decodeInteger(reader, relative) {
40
+ let value = 0;
41
+ let shift = 0;
42
+ let integer = 0;
43
+ do {
44
+ const c = reader.next();
45
+ integer = charToInt[c];
46
+ value |= (integer & 31) << shift;
47
+ shift += 5;
48
+ } while (integer & 32);
49
+ const shouldNegate = value & 1;
50
+ value >>>= 1;
51
+ if (shouldNegate) {
52
+ value = -2147483648 | -value;
53
+ }
54
+ return relative + value;
55
+ }
56
+ function hasMoreVlq(reader, max) {
57
+ if (reader.pos >= max)
58
+ return false;
59
+ return reader.peek() !== comma;
60
+ }
61
+ var bufLength = 1024 * 16;
62
+ var StringReader = class {
63
+ constructor(buffer) {
64
+ this.pos = 0;
65
+ this.buffer = buffer;
66
+ }
67
+ next() {
68
+ return this.buffer.charCodeAt(this.pos++);
69
+ }
70
+ peek() {
71
+ return this.buffer.charCodeAt(this.pos);
72
+ }
73
+ indexOf(char) {
74
+ const { buffer, pos } = this;
75
+ const idx = buffer.indexOf(char, pos);
76
+ return idx === -1 ? buffer.length : idx;
77
+ }
78
+ };
79
+ function decode(mappings) {
80
+ const { length } = mappings;
81
+ const reader = new StringReader(mappings);
82
+ const decoded = [];
83
+ let genColumn = 0;
84
+ let sourcesIndex = 0;
85
+ let sourceLine = 0;
86
+ let sourceColumn = 0;
87
+ let namesIndex = 0;
88
+ do {
89
+ const semi = reader.indexOf(";");
90
+ const line = [];
91
+ let sorted = true;
92
+ let lastCol = 0;
93
+ genColumn = 0;
94
+ while (reader.pos < semi) {
95
+ let seg;
96
+ genColumn = decodeInteger(reader, genColumn);
97
+ if (genColumn < lastCol)
98
+ sorted = false;
99
+ lastCol = genColumn;
100
+ if (hasMoreVlq(reader, semi)) {
101
+ sourcesIndex = decodeInteger(reader, sourcesIndex);
102
+ sourceLine = decodeInteger(reader, sourceLine);
103
+ sourceColumn = decodeInteger(reader, sourceColumn);
104
+ if (hasMoreVlq(reader, semi)) {
105
+ namesIndex = decodeInteger(reader, namesIndex);
106
+ seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
107
+ } else {
108
+ seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
109
+ }
110
+ } else {
111
+ seg = [genColumn];
112
+ }
113
+ line.push(seg);
114
+ reader.pos++;
115
+ }
116
+ if (!sorted)
117
+ sort(line);
118
+ decoded.push(line);
119
+ reader.pos = semi + 1;
120
+ } while (reader.pos <= length);
121
+ return decoded;
122
+ }
123
+ function sort(line) {
124
+ line.sort(sortComparator);
125
+ }
126
+ function sortComparator(a, b) {
127
+ return a[0] - b[0];
128
+ }
129
+
130
+ // ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
131
+ var schemeRegex = /^[\w+.-]+:\/\//;
132
+ var urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
133
+ var fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
134
+ function isAbsoluteUrl(input) {
135
+ return schemeRegex.test(input);
136
+ }
137
+ function isSchemeRelativeUrl(input) {
138
+ return input.startsWith("//");
139
+ }
140
+ function isAbsolutePath(input) {
141
+ return input.startsWith("/");
142
+ }
143
+ function isFileUrl(input) {
144
+ return input.startsWith("file:");
145
+ }
146
+ function isRelative(input) {
147
+ return /^[.?#]/.test(input);
148
+ }
149
+ function parseAbsoluteUrl(input) {
150
+ const match = urlRegex.exec(input);
151
+ return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
152
+ }
153
+ function parseFileUrl(input) {
154
+ const match = fileRegex.exec(input);
155
+ const path = match[2];
156
+ return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
157
+ }
158
+ function makeUrl(scheme, user, host, port, path, query, hash) {
159
+ return {
160
+ scheme,
161
+ user,
162
+ host,
163
+ port,
164
+ path,
165
+ query,
166
+ hash,
167
+ type: 7
168
+ };
169
+ }
170
+ function parseUrl(input) {
171
+ if (isSchemeRelativeUrl(input)) {
172
+ const url2 = parseAbsoluteUrl("http:" + input);
173
+ url2.scheme = "";
174
+ url2.type = 6;
175
+ return url2;
176
+ }
177
+ if (isAbsolutePath(input)) {
178
+ const url2 = parseAbsoluteUrl("http://foo.com" + input);
179
+ url2.scheme = "";
180
+ url2.host = "";
181
+ url2.type = 5;
182
+ return url2;
183
+ }
184
+ if (isFileUrl(input))
185
+ return parseFileUrl(input);
186
+ if (isAbsoluteUrl(input))
187
+ return parseAbsoluteUrl(input);
188
+ const url = parseAbsoluteUrl("http://foo.com/" + input);
189
+ url.scheme = "";
190
+ url.host = "";
191
+ url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
192
+ return url;
193
+ }
194
+ function stripPathFilename(path) {
195
+ if (path.endsWith("/.."))
196
+ return path;
197
+ const index = path.lastIndexOf("/");
198
+ return path.slice(0, index + 1);
199
+ }
200
+ function mergePaths(url, base) {
201
+ normalizePath(base, base.type);
202
+ if (url.path === "/") {
203
+ url.path = base.path;
204
+ } else {
205
+ url.path = stripPathFilename(base.path) + url.path;
206
+ }
207
+ }
208
+ function normalizePath(url, type) {
209
+ const rel = type <= 4;
210
+ const pieces = url.path.split("/");
211
+ let pointer = 1;
212
+ let positive = 0;
213
+ let addTrailingSlash = false;
214
+ for (let i = 1;i < pieces.length; i++) {
215
+ const piece = pieces[i];
216
+ if (!piece) {
217
+ addTrailingSlash = true;
218
+ continue;
219
+ }
220
+ addTrailingSlash = false;
221
+ if (piece === ".")
222
+ continue;
223
+ if (piece === "..") {
224
+ if (positive) {
225
+ addTrailingSlash = true;
226
+ positive--;
227
+ pointer--;
228
+ } else if (rel) {
229
+ pieces[pointer++] = piece;
230
+ }
231
+ continue;
232
+ }
233
+ pieces[pointer++] = piece;
234
+ positive++;
235
+ }
236
+ let path = "";
237
+ for (let i = 1;i < pointer; i++) {
238
+ path += "/" + pieces[i];
239
+ }
240
+ if (!path || addTrailingSlash && !path.endsWith("/..")) {
241
+ path += "/";
242
+ }
243
+ url.path = path;
244
+ }
245
+ function resolve(input, base) {
246
+ if (!input && !base)
247
+ return "";
248
+ const url = parseUrl(input);
249
+ let inputType = url.type;
250
+ if (base && inputType !== 7) {
251
+ const baseUrl = parseUrl(base);
252
+ const baseType = baseUrl.type;
253
+ switch (inputType) {
254
+ case 1:
255
+ url.hash = baseUrl.hash;
256
+ case 2:
257
+ url.query = baseUrl.query;
258
+ case 3:
259
+ case 4:
260
+ mergePaths(url, baseUrl);
261
+ case 5:
262
+ url.user = baseUrl.user;
263
+ url.host = baseUrl.host;
264
+ url.port = baseUrl.port;
265
+ case 6:
266
+ url.scheme = baseUrl.scheme;
267
+ }
268
+ if (baseType > inputType)
269
+ inputType = baseType;
270
+ }
271
+ normalizePath(url, inputType);
272
+ const queryHash = url.query + url.hash;
273
+ switch (inputType) {
274
+ case 2:
275
+ case 3:
276
+ return queryHash;
277
+ case 4: {
278
+ const path = url.path.slice(1);
279
+ if (!path)
280
+ return queryHash || ".";
281
+ if (isRelative(base || input) && !isRelative(path)) {
282
+ return "./" + path + queryHash;
283
+ }
284
+ return path + queryHash;
285
+ }
286
+ case 5:
287
+ return url.path + queryHash;
288
+ default:
289
+ return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
290
+ }
291
+ }
292
+
293
+ // ../../node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
294
+ function stripFilename(path) {
295
+ if (!path)
296
+ return "";
297
+ const index = path.lastIndexOf("/");
298
+ return path.slice(0, index + 1);
299
+ }
300
+ function resolver(mapUrl, sourceRoot) {
301
+ const from = stripFilename(mapUrl);
302
+ const prefix = sourceRoot ? sourceRoot + "/" : "";
303
+ return (source) => resolve(prefix + (source || ""), from);
304
+ }
305
+ var COLUMN = 0;
306
+ var SOURCES_INDEX = 1;
307
+ var SOURCE_LINE = 2;
308
+ var SOURCE_COLUMN = 3;
309
+ var NAMES_INDEX = 4;
310
+ function maybeSort(mappings, owned) {
311
+ const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
312
+ if (unsortedIndex === mappings.length)
313
+ return mappings;
314
+ if (!owned)
315
+ mappings = mappings.slice();
316
+ for (let i = unsortedIndex;i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
317
+ mappings[i] = sortSegments(mappings[i], owned);
318
+ }
319
+ return mappings;
320
+ }
321
+ function nextUnsortedSegmentLine(mappings, start) {
322
+ for (let i = start;i < mappings.length; i++) {
323
+ if (!isSorted(mappings[i]))
324
+ return i;
325
+ }
326
+ return mappings.length;
327
+ }
328
+ function isSorted(line) {
329
+ for (let j = 1;j < line.length; j++) {
330
+ if (line[j][COLUMN] < line[j - 1][COLUMN]) {
331
+ return false;
332
+ }
333
+ }
334
+ return true;
335
+ }
336
+ function sortSegments(line, owned) {
337
+ if (!owned)
338
+ line = line.slice();
339
+ return line.sort(sortComparator2);
340
+ }
341
+ function sortComparator2(a, b) {
342
+ return a[COLUMN] - b[COLUMN];
343
+ }
344
+ var found = false;
345
+ function binarySearch(haystack, needle, low, high) {
346
+ while (low <= high) {
347
+ const mid = low + (high - low >> 1);
348
+ const cmp = haystack[mid][COLUMN] - needle;
349
+ if (cmp === 0) {
350
+ found = true;
351
+ return mid;
352
+ }
353
+ if (cmp < 0) {
354
+ low = mid + 1;
355
+ } else {
356
+ high = mid - 1;
357
+ }
358
+ }
359
+ found = false;
360
+ return low - 1;
361
+ }
362
+ function upperBound(haystack, needle, index) {
363
+ for (let i = index + 1;i < haystack.length; index = i++) {
364
+ if (haystack[i][COLUMN] !== needle)
365
+ break;
366
+ }
367
+ return index;
368
+ }
369
+ function lowerBound(haystack, needle, index) {
370
+ for (let i = index - 1;i >= 0; index = i--) {
371
+ if (haystack[i][COLUMN] !== needle)
372
+ break;
373
+ }
374
+ return index;
375
+ }
376
+ function memoizedState() {
377
+ return {
378
+ lastKey: -1,
379
+ lastNeedle: -1,
380
+ lastIndex: -1
381
+ };
382
+ }
383
+ function memoizedBinarySearch(haystack, needle, state, key) {
384
+ const { lastKey, lastNeedle, lastIndex } = state;
385
+ let low = 0;
386
+ let high = haystack.length - 1;
387
+ if (key === lastKey) {
388
+ if (needle === lastNeedle) {
389
+ found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
390
+ return lastIndex;
391
+ }
392
+ if (needle >= lastNeedle) {
393
+ low = lastIndex === -1 ? 0 : lastIndex;
394
+ } else {
395
+ high = lastIndex;
396
+ }
397
+ }
398
+ state.lastKey = key;
399
+ state.lastNeedle = needle;
400
+ return state.lastIndex = binarySearch(haystack, needle, low, high);
401
+ }
402
+ function parse(map) {
403
+ return typeof map === "string" ? JSON.parse(map) : map;
404
+ }
405
+ var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
406
+ var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
407
+ var LEAST_UPPER_BOUND = -1;
408
+ var GREATEST_LOWER_BOUND = 1;
409
+ var TraceMap = class {
410
+ constructor(map, mapUrl) {
411
+ const isString = typeof map === "string";
412
+ if (!isString && map._decodedMemo)
413
+ return map;
414
+ const parsed = parse(map);
415
+ const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
416
+ this.version = version;
417
+ this.file = file;
418
+ this.names = names || [];
419
+ this.sourceRoot = sourceRoot;
420
+ this.sources = sources;
421
+ this.sourcesContent = sourcesContent;
422
+ this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || undefined;
423
+ const resolve2 = resolver(mapUrl, sourceRoot);
424
+ this.resolvedSources = sources.map(resolve2);
425
+ const { mappings } = parsed;
426
+ if (typeof mappings === "string") {
427
+ this._encoded = mappings;
428
+ this._decoded = undefined;
429
+ } else if (Array.isArray(mappings)) {
430
+ this._encoded = undefined;
431
+ this._decoded = maybeSort(mappings, isString);
432
+ } else if (parsed.sections) {
433
+ throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
434
+ } else {
435
+ throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
436
+ }
437
+ this._decodedMemo = memoizedState();
438
+ this._bySources = undefined;
439
+ this._bySourceMemos = undefined;
440
+ }
441
+ };
442
+ function cast(map) {
443
+ return map;
444
+ }
445
+ function decodedMappings(map) {
446
+ var _a;
447
+ return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
448
+ }
449
+ function originalPositionFor(map, needle) {
450
+ let { line, column, bias } = needle;
451
+ line--;
452
+ if (line < 0)
453
+ throw new Error(LINE_GTR_ZERO);
454
+ if (column < 0)
455
+ throw new Error(COL_GTR_EQ_ZERO);
456
+ const decoded = decodedMappings(map);
457
+ if (line >= decoded.length)
458
+ return OMapping(null, null, null, null);
459
+ const segments = decoded[line];
460
+ const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
461
+ if (index === -1)
462
+ return OMapping(null, null, null, null);
463
+ const segment = segments[index];
464
+ if (segment.length === 1)
465
+ return OMapping(null, null, null, null);
466
+ const { names, resolvedSources } = map;
467
+ return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
468
+ }
469
+ function sourceIndex(map, source) {
470
+ const { sources, resolvedSources } = map;
471
+ let index = sources.indexOf(source);
472
+ if (index === -1)
473
+ index = resolvedSources.indexOf(source);
474
+ return index;
475
+ }
476
+ function sourceContentFor(map, source) {
477
+ const { sourcesContent } = map;
478
+ if (sourcesContent == null)
479
+ return null;
480
+ const index = sourceIndex(map, source);
481
+ return index === -1 ? null : sourcesContent[index];
482
+ }
483
+ function OMapping(source, line, column, name) {
484
+ return { source, line, column, name };
485
+ }
486
+ function traceSegmentInternal(segments, memo, line, column, bias) {
487
+ let index = memoizedBinarySearch(segments, column, memo, line);
488
+ if (found) {
489
+ index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
490
+ } else if (bias === LEAST_UPPER_BOUND)
491
+ index++;
492
+ if (index === -1 || index === segments.length)
493
+ return -1;
494
+ return index;
495
+ }
496
+
497
+ // src/feature/on-error-log/server/sourcemap.ts
498
+ var FRAME = /^(\s*at\s+(?:async\s+)?)(?:(.*?)\s+\()?(?:file:\/\/)?\/var\/task\/([^\s:)]+):(\d+):(\d+)(\)?)\s*$/;
499
+ var MESSAGE_TEMPLATES = /^([A-Za-z_$][\w$]{0,2}) (is not a (?:function|constructor)|is not defined|is not iterable)/;
500
+ var createSymbolicator = (loaders) => {
501
+ const prefixes = new Map;
502
+ const maps = new Map;
503
+ const bound = (cache, limit) => {
504
+ while (cache.size > limit) {
505
+ cache.delete(cache.keys().next().value);
506
+ }
507
+ };
508
+ const prefixFor = (functionName, version) => {
509
+ const key = `${functionName}:${version}`;
510
+ if (!prefixes.has(key)) {
511
+ const promise = loaders.loadPrefix(functionName, version);
512
+ promise.then((prefix) => prefix === undefined && prefixes.delete(key), () => prefixes.delete(key));
513
+ prefixes.set(key, promise);
514
+ bound(prefixes, 100);
515
+ }
516
+ return prefixes.get(key);
517
+ };
518
+ const mapFor = (key) => {
519
+ if (!maps.has(key)) {
520
+ const promise = loaders.loadMap(key).then((json) => json ? new TraceMap(JSON.parse(json)) : undefined);
521
+ promise.catch(() => maps.delete(key));
522
+ maps.set(key, promise);
523
+ bound(maps, 6);
524
+ }
525
+ return maps.get(key);
526
+ };
527
+ const KEYWORDS = new Set([
528
+ "new",
529
+ "return",
530
+ "throw",
531
+ "await",
532
+ "async",
533
+ "typeof",
534
+ "void",
535
+ "delete",
536
+ "const",
537
+ "let",
538
+ "var",
539
+ "function",
540
+ "class",
541
+ "this",
542
+ "super",
543
+ "yield",
544
+ "if",
545
+ "else",
546
+ "for",
547
+ "while",
548
+ "do",
549
+ "switch",
550
+ "case",
551
+ "try",
552
+ "catch",
553
+ "finally",
554
+ "in",
555
+ "of",
556
+ "import",
557
+ "export",
558
+ "default",
559
+ "extends",
560
+ "static",
561
+ "break",
562
+ "continue",
563
+ "debugger",
564
+ "instanceof",
565
+ "null",
566
+ "true",
567
+ "false",
568
+ "undefined",
569
+ "get",
570
+ "set"
571
+ ]);
572
+ const identifierAt = (map, position) => {
573
+ if (position.name) {
574
+ return position.name;
575
+ }
576
+ const content = sourceContentFor(map, position.source);
577
+ const line = content?.split(`
578
+ `)[position.line - 1];
579
+ const token = line?.slice(position.column ?? 0).match(/^[A-Za-z_$][\w$]*/)?.[0];
580
+ return token && !KEYWORDS.has(token) ? token : undefined;
581
+ };
582
+ const cleanSource = (source) => {
583
+ const path = source.split("?")[0];
584
+ const nested = path.lastIndexOf("node_modules/");
585
+ if (nested >= 0) {
586
+ return path.slice(nested + "node_modules/".length);
587
+ }
588
+ return path.replace(/^(\.\.\/)+/, "");
589
+ };
590
+ return async (error) => {
591
+ const passthrough = { message: error.message, stackTrace: error.stackTrace };
592
+ try {
593
+ if (!error.stackTrace?.length) {
594
+ return passthrough;
595
+ }
596
+ const prefix = await prefixFor(error.functionName, error.version);
597
+ if (!prefix) {
598
+ return passthrough;
599
+ }
600
+ const resolved = await Promise.all(error.stackTrace.map(async (line) => {
601
+ const match = FRAME.exec(line);
602
+ if (!match) {
603
+ return;
604
+ }
605
+ const [, at, caller, file, lineNo, columnNo] = match;
606
+ const map = await mapFor(`${prefix}${file}.map`).catch(() => {
607
+ return;
608
+ });
609
+ if (!map) {
610
+ return;
611
+ }
612
+ const position = originalPositionFor(map, {
613
+ line: Number(lineNo),
614
+ column: Number(columnNo) - 1
615
+ });
616
+ if (position.source === null || position.line === null) {
617
+ return;
618
+ }
619
+ const source = cleanSource(position.source);
620
+ return {
621
+ at,
622
+ caller,
623
+ location: `${source}:${position.line}:${(position.column ?? 0) + 1}`,
624
+ callee: identifierAt(map, { ...position, source: position.source, line: position.line })
625
+ };
626
+ }));
627
+ const stackTrace = error.stackTrace.map((line, index) => {
628
+ const frame = resolved[index];
629
+ if (!frame) {
630
+ return line;
631
+ }
632
+ const name = resolved[index + 1]?.callee ?? frame.caller;
633
+ return name ? `${frame.at}${name} (${frame.location})` : `${frame.at}${frame.location}`;
634
+ });
635
+ const headerType = error.stackTrace[0]?.match(/^([A-Z][\w$]*Error): /)?.[1];
636
+ const type = error.type === undefined || /Error$/.test(error.type) ? error.type : headerType;
637
+ const engineError = type === undefined || type === "TypeError" || type === "ReferenceError";
638
+ let message = error.message;
639
+ const template = engineError ? MESSAGE_TEMPLATES.exec(message) : null;
640
+ const firstFrame = error.stackTrace.findIndex((line) => FRAME.test(line));
641
+ const top = firstFrame >= 0 ? resolved[firstFrame] : undefined;
642
+ if (template && top?.callee) {
643
+ message = `${top.callee} ${template[2]}${message.slice(template[0].length)}`;
644
+ if (stackTrace[0] && !resolved[0] && stackTrace[0].endsWith(error.message)) {
645
+ stackTrace[0] = stackTrace[0].slice(0, -error.message.length) + message;
646
+ }
647
+ }
648
+ return { message, stackTrace };
649
+ } catch {
650
+ return passthrough;
651
+ }
652
+ };
653
+ };
654
+
655
+ // src/feature/on-error-log/server/handle.ts
19
656
  var RuntimeErrorSchema = object({
20
657
  timestamp: string(),
21
658
  level: pipe(string(), toLowerCase(), picklist(["error", "warn", "fatal"])),
@@ -43,13 +680,45 @@ var SystemErrorSchema = object({
43
680
  });
44
681
  var EventSchema = object({
45
682
  logGroup: string(),
683
+ logStream: optional(string()),
46
684
  logEvents: array(object({
47
685
  id: string(),
48
686
  message: string(),
49
687
  timestamp: pipe(number(), transform((v) => new Date(v)))
50
688
  }))
51
689
  });
52
- var createHandler = (consumer) => {
690
+ var createAwsLoaders = async () => {
691
+ const { GetObjectCommand, S3Client } = await import("@aws-sdk/client-s3");
692
+ const s3 = new S3Client({});
693
+ const bucket = process.env.SOURCEMAP_BUCKET;
694
+ const read = async (key) => {
695
+ try {
696
+ const result = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
697
+ return result.Body?.transformToString();
698
+ } catch (error) {
699
+ if (error.name === "NoSuchKey" || error.name === "NotFound") {
700
+ return;
701
+ }
702
+ throw error;
703
+ }
704
+ };
705
+ return {
706
+ loadPrefix(functionName, version) {
707
+ return read(formatSourcemapVersionKey(functionName, version));
708
+ },
709
+ loadMap(key) {
710
+ return read(key);
711
+ }
712
+ };
713
+ };
714
+ var createHandler = (consumer, loaders) => {
715
+ let symbolicator;
716
+ const getSymbolicator = async () => {
717
+ if (!symbolicator && (loaders || process.env.SOURCEMAP_BUCKET)) {
718
+ symbolicator = createSymbolicator(loaders ?? await createAwsLoaders());
719
+ }
720
+ return symbolicator;
721
+ };
53
722
  return async (event, context) => {
54
723
  try {
55
724
  const payload = Buffer.from(event.awslogs.data, "base64");
@@ -60,11 +729,38 @@ var createHandler = (consumer) => {
60
729
  return;
61
730
  }
62
731
  const origin = result.output.logGroup.split("/").pop();
732
+ const version = result.output.logStream?.match(/\[([^\]]+)\]/)?.[1];
63
733
  for (const logEvent of result.output.logEvents) {
64
734
  const error = parseError(logEvent.message, origin);
65
735
  if (!error) {
66
736
  continue;
67
737
  }
738
+ if (error.stackTrace?.length && version) {
739
+ try {
740
+ const mapper = await getSymbolicator();
741
+ if (mapper) {
742
+ const mapped = await Promise.race([
743
+ mapper({
744
+ functionName: origin,
745
+ version,
746
+ type: error.type,
747
+ message: error.message,
748
+ stackTrace: error.stackTrace
749
+ }),
750
+ new Promise((resolve2) => setTimeout(() => resolve2(undefined), 3000))
751
+ ]);
752
+ if (mapped) {
753
+ const didMap = mapped.stackTrace !== error.stackTrace;
754
+ error.message = mapped.message;
755
+ error.stackTrace = mapped.stackTrace;
756
+ const header = mapped.stackTrace?.[0]?.match(/^([A-Z][\w$]*Error): /);
757
+ if (didMap && header && !/Error$/.test(error.type)) {
758
+ error.type = header[1];
759
+ }
760
+ }
761
+ }
762
+ } catch {}
763
+ }
68
764
  const invoke = Promise.resolve().then(() => {
69
765
  return consumer({
70
766
  ...error,
@@ -72,7 +768,7 @@ var createHandler = (consumer) => {
72
768
  });
73
769
  }).catch((error2) => console.error("The on-error-log consumer failed", error2));
74
770
  const deadline = Math.max(0, context.getRemainingTimeInMillis() - 3000);
75
- await Promise.race([invoke, new Promise((resolve) => setTimeout(resolve, deadline))]);
771
+ await Promise.race([invoke, new Promise((resolve2) => setTimeout(resolve2, deadline))]);
76
772
  }
77
773
  } catch (error) {
78
774
  console.warn("Failed to consume the error logs", error);
@@ -94,6 +790,7 @@ var parseError = (message, origin) => {
94
790
  origin = extra.route;
95
791
  delete extra.route;
96
792
  }
793
+ delete extra.name;
97
794
  const hash = createHash("sha256").update([origin, errorType, errorMessage, stackTrace].join("-")).digest("hex");
98
795
  return {
99
796
  hash,