@jsenv/test 3.3.17 → 3.3.19

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,932 +0,0 @@
1
- /*
2
- * Link to things doing pattern matching:
3
- * https://git-scm.com/docs/gitignore
4
- * https://github.com/kaelzhang/node-ignore
5
- */
6
-
7
- /** @module jsenv_url_meta **/
8
- /**
9
- * An object representing the result of applying a pattern to an url
10
- * @typedef {Object} MatchResult
11
- * @property {boolean} matched Indicates if url matched pattern
12
- * @property {number} patternIndex Index where pattern stopped matching url, otherwise pattern.length
13
- * @property {number} urlIndex Index where url stopped matching pattern, otherwise url.length
14
- * @property {Array} matchGroups Array of strings captured during pattern matching
15
- */
16
-
17
- /**
18
- * Apply a pattern to an url
19
- * @param {Object} applyPatternMatchingParams
20
- * @param {string} applyPatternMatchingParams.pattern "*", "**" and trailing slash have special meaning
21
- * @param {string} applyPatternMatchingParams.url a string representing an url
22
- * @return {MatchResult}
23
- */
24
- const applyPattern = ({ url, pattern }) => {
25
- const { matched, patternIndex, index, groups } = applyMatching(pattern, url);
26
- const matchGroups = [];
27
- let groupIndex = 0;
28
- for (const group of groups) {
29
- if (group.name) {
30
- matchGroups[group.name] = group.string;
31
- } else {
32
- matchGroups[groupIndex] = group.string;
33
- groupIndex++;
34
- }
35
- }
36
- return {
37
- matched,
38
- patternIndex,
39
- urlIndex: index,
40
- matchGroups,
41
- };
42
- };
43
-
44
- const applyMatching = (pattern, string) => {
45
- const groups = [];
46
- let patternIndex = 0;
47
- let index = 0;
48
- let remainingPattern = pattern;
49
- let remainingString = string;
50
- let restoreIndexes = true;
51
-
52
- const consumePattern = (count) => {
53
- const subpattern = remainingPattern.slice(0, count);
54
- remainingPattern = remainingPattern.slice(count);
55
- patternIndex += count;
56
- return subpattern;
57
- };
58
- const consumeString = (count) => {
59
- const substring = remainingString.slice(0, count);
60
- remainingString = remainingString.slice(count);
61
- index += count;
62
- return substring;
63
- };
64
- const consumeRemainingString = () => {
65
- return consumeString(remainingString.length);
66
- };
67
-
68
- let matched;
69
- const iterate = () => {
70
- const patternIndexBefore = patternIndex;
71
- const indexBefore = index;
72
- matched = matchOne();
73
- if (matched === undefined) {
74
- consumePattern(1);
75
- consumeString(1);
76
- iterate();
77
- return;
78
- }
79
- if (matched === false && restoreIndexes) {
80
- patternIndex = patternIndexBefore;
81
- index = indexBefore;
82
- }
83
- };
84
- const matchOne = () => {
85
- // pattern consumed and string consumed
86
- if (remainingPattern === "" && remainingString === "") {
87
- return true; // string fully matched pattern
88
- }
89
- // pattern consumed, string not consumed
90
- if (remainingPattern === "" && remainingString !== "") {
91
- return false; // fails because string longer than expect
92
- }
93
- // -- from this point pattern is not consumed --
94
- // string consumed, pattern not consumed
95
- if (remainingString === "") {
96
- if (remainingPattern === "**") {
97
- // trailing "**" is optional
98
- consumePattern(2);
99
- return true;
100
- }
101
- if (remainingPattern === "*") {
102
- groups.push({ string: "" });
103
- }
104
- return false; // fail because string shorter than expect
105
- }
106
- // -- from this point pattern and string are not consumed --
107
- // fast path trailing slash
108
- if (remainingPattern === "/") {
109
- if (remainingString[0] === "/") {
110
- // trailing slash match remaining
111
- consumePattern(1);
112
- groups.push({ string: consumeRemainingString() });
113
- return true;
114
- }
115
- return false;
116
- }
117
- // fast path trailing '**'
118
- if (remainingPattern === "**") {
119
- consumePattern(2);
120
- consumeRemainingString();
121
- return true;
122
- }
123
- if (remainingPattern.slice(0, 4) === "/**/") {
124
- consumePattern(3); // consumes "/**/"
125
- const skipResult = skipUntilMatch({
126
- pattern: remainingPattern,
127
- string: remainingString,
128
- canSkipSlash: true,
129
- });
130
- groups.push(...skipResult.groups);
131
- consumePattern(skipResult.patternIndex);
132
- consumeRemainingString();
133
- restoreIndexes = false;
134
- return skipResult.matched;
135
- }
136
- // pattern leading **
137
- if (remainingPattern.slice(0, 2) === "**") {
138
- consumePattern(2); // consumes "**"
139
- let skipAllowed = true;
140
- if (remainingPattern[0] === "/") {
141
- consumePattern(1); // consumes "/"
142
- // when remainingPattern was preceeded by "**/"
143
- // and remainingString have no "/"
144
- // then skip is not allowed, a regular match will be performed
145
- if (!remainingString.includes("/")) {
146
- skipAllowed = false;
147
- }
148
- }
149
- // pattern ending with "**" or "**/" match remaining string
150
- if (remainingPattern === "") {
151
- consumeRemainingString();
152
- return true;
153
- }
154
- if (skipAllowed) {
155
- const skipResult = skipUntilMatch({
156
- pattern: remainingPattern,
157
- string: remainingString,
158
- canSkipSlash: true,
159
- });
160
- groups.push(...skipResult.groups);
161
- consumePattern(skipResult.patternIndex);
162
- consumeRemainingString();
163
- restoreIndexes = false;
164
- return skipResult.matched;
165
- }
166
- }
167
- if (remainingPattern[0] === "*") {
168
- consumePattern(1); // consumes "*"
169
- if (remainingPattern === "") {
170
- // matches everything except "/"
171
- const slashIndex = remainingString.indexOf("/");
172
- if (slashIndex === -1) {
173
- groups.push({ string: consumeRemainingString() });
174
- return true;
175
- }
176
- groups.push({ string: consumeString(slashIndex) });
177
- return false;
178
- }
179
- // the next char must not the one expect by remainingPattern[0]
180
- // because * is greedy and expect to skip at least one char
181
- if (remainingPattern[0] === remainingString[0]) {
182
- groups.push({ string: "" });
183
- patternIndex = patternIndex - 1;
184
- return false;
185
- }
186
- const skipResult = skipUntilMatch({
187
- pattern: remainingPattern,
188
- string: remainingString,
189
- canSkipSlash: false,
190
- });
191
- groups.push(skipResult.group, ...skipResult.groups);
192
- consumePattern(skipResult.patternIndex);
193
- consumeString(skipResult.index);
194
- restoreIndexes = false;
195
- return skipResult.matched;
196
- }
197
- if (remainingPattern[0] !== remainingString[0]) {
198
- return false;
199
- }
200
- return undefined;
201
- };
202
- iterate();
203
-
204
- return {
205
- matched,
206
- patternIndex,
207
- index,
208
- groups,
209
- };
210
- };
211
-
212
- const skipUntilMatch = ({ pattern, string, canSkipSlash }) => {
213
- let index = 0;
214
- let remainingString = string;
215
- let longestAttemptRange = null;
216
- let isLastAttempt = false;
217
-
218
- const failure = () => {
219
- return {
220
- matched: false,
221
- patternIndex: longestAttemptRange.patternIndex,
222
- index: longestAttemptRange.index + longestAttemptRange.length,
223
- groups: longestAttemptRange.groups,
224
- group: {
225
- string: string.slice(0, longestAttemptRange.index),
226
- },
227
- };
228
- };
229
-
230
- const tryToMatch = () => {
231
- const matchAttempt = applyMatching(pattern, remainingString);
232
- if (matchAttempt.matched) {
233
- return {
234
- matched: true,
235
- patternIndex: matchAttempt.patternIndex,
236
- index: index + matchAttempt.index,
237
- groups: matchAttempt.groups,
238
- group: {
239
- string:
240
- remainingString === ""
241
- ? string
242
- : string.slice(0, -remainingString.length),
243
- },
244
- };
245
- }
246
- const attemptIndex = matchAttempt.index;
247
- const attemptRange = {
248
- patternIndex: matchAttempt.patternIndex,
249
- index,
250
- length: attemptIndex,
251
- groups: matchAttempt.groups,
252
- };
253
- if (
254
- !longestAttemptRange ||
255
- longestAttemptRange.length < attemptRange.length
256
- ) {
257
- longestAttemptRange = attemptRange;
258
- }
259
- if (isLastAttempt) {
260
- return failure();
261
- }
262
- const nextIndex = attemptIndex + 1;
263
- if (nextIndex >= remainingString.length) {
264
- return failure();
265
- }
266
- if (remainingString[0] === "/") {
267
- if (!canSkipSlash) {
268
- return failure();
269
- }
270
- // when it's the last slash, the next attempt is the last
271
- if (remainingString.indexOf("/", 1) === -1) {
272
- isLastAttempt = true;
273
- }
274
- }
275
- // search against the next unattempted string
276
- index += nextIndex;
277
- remainingString = remainingString.slice(nextIndex);
278
- return tryToMatch();
279
- };
280
- return tryToMatch();
281
- };
282
-
283
- const applyPatternMatching = ({ url, pattern }) => {
284
- assertUrlLike(pattern, "pattern");
285
- if (url && typeof url.href === "string") url = url.href;
286
- assertUrlLike(url, "url");
287
- return applyPattern({ url, pattern });
288
- };
289
-
290
- const resolveAssociations = (associations, baseUrl) => {
291
- if (baseUrl && typeof baseUrl.href === "string") baseUrl = baseUrl.href;
292
- assertUrlLike(baseUrl, "baseUrl");
293
-
294
- const associationsResolved = {};
295
- for (const key of Object.keys(associations)) {
296
- const value = associations[key];
297
- if (typeof value === "object" && value !== null) {
298
- const valueMapResolved = {};
299
- for (const pattern of Object.keys(value)) {
300
- const valueAssociated = value[pattern];
301
- let patternResolved;
302
- try {
303
- patternResolved = String(new URL(pattern, baseUrl));
304
- } catch (e) {
305
- // it's not really an url, no need to perform url resolution nor encoding
306
- patternResolved = pattern;
307
- }
308
-
309
- valueMapResolved[patternResolved] = valueAssociated;
310
- }
311
- associationsResolved[key] = valueMapResolved;
312
- } else {
313
- associationsResolved[key] = value;
314
- }
315
- }
316
- return associationsResolved;
317
- };
318
-
319
- const asFlatAssociations = (associations) => {
320
- if (!isPlainObject(associations)) {
321
- throw new TypeError(
322
- `associations must be a plain object, got ${associations}`,
323
- );
324
- }
325
- const flatAssociations = {};
326
- for (const associationName of Object.keys(associations)) {
327
- const associationValue = associations[associationName];
328
- if (!isPlainObject(associationValue)) {
329
- continue;
330
- }
331
- for (const pattern of Object.keys(associationValue)) {
332
- const patternValue = associationValue[pattern];
333
- const previousValue = flatAssociations[pattern];
334
- if (isPlainObject(previousValue)) {
335
- flatAssociations[pattern] = {
336
- ...previousValue,
337
- [associationName]: patternValue,
338
- };
339
- } else {
340
- flatAssociations[pattern] = {
341
- [associationName]: patternValue,
342
- };
343
- }
344
- }
345
- }
346
- return flatAssociations;
347
- };
348
-
349
- const applyAssociations = ({ url, associations }) => {
350
- if (url && typeof url.href === "string") url = url.href;
351
- assertUrlLike(url);
352
- const flatAssociations = asFlatAssociations(associations);
353
- let associatedValue = {};
354
- for (const pattern of Object.keys(flatAssociations)) {
355
- const { matched } = applyPatternMatching({
356
- pattern,
357
- url,
358
- });
359
- if (matched) {
360
- const value = flatAssociations[pattern];
361
- associatedValue = deepAssign(associatedValue, value);
362
- }
363
- }
364
- return associatedValue;
365
- };
366
-
367
- const deepAssign = (firstValue, secondValue) => {
368
- if (!isPlainObject(firstValue) || !isPlainObject(secondValue)) {
369
- return secondValue;
370
- }
371
- for (const key of Object.keys(secondValue)) {
372
- const leftValue = firstValue[key];
373
- const rightValue = secondValue[key];
374
- firstValue[key] = deepAssign(leftValue, rightValue);
375
- }
376
- return firstValue;
377
- };
378
-
379
- const urlChildMayMatch = ({ url, associations, predicate }) => {
380
- if (url && typeof url.href === "string") url = url.href;
381
- assertUrlLike(url, "url");
382
- // the function was meants to be used on url ending with '/'
383
- if (!url.endsWith("/")) {
384
- throw new Error(`url should end with /, got ${url}`);
385
- }
386
- if (typeof predicate !== "function") {
387
- throw new TypeError(`predicate must be a function, got ${predicate}`);
388
- }
389
- const flatAssociations = asFlatAssociations(associations);
390
- // for full match we must create an object to allow pattern to override previous ones
391
- let fullMatchMeta = {};
392
- let someFullMatch = false;
393
- // for partial match, any meta satisfying predicate will be valid because
394
- // we don't know for sure if pattern will still match for a file inside pathname
395
- const partialMatchMetaArray = [];
396
- for (const pattern of Object.keys(flatAssociations)) {
397
- const value = flatAssociations[pattern];
398
- const matchResult = applyPatternMatching({
399
- pattern,
400
- url,
401
- });
402
- if (matchResult.matched) {
403
- someFullMatch = true;
404
- if (isPlainObject(fullMatchMeta) && isPlainObject(value)) {
405
- fullMatchMeta = {
406
- ...fullMatchMeta,
407
- ...value,
408
- };
409
- } else {
410
- fullMatchMeta = value;
411
- }
412
- } else if (someFullMatch === false && matchResult.urlIndex >= url.length) {
413
- partialMatchMetaArray.push(value);
414
- }
415
- }
416
- if (someFullMatch) {
417
- return Boolean(predicate(fullMatchMeta));
418
- }
419
- return partialMatchMetaArray.some((partialMatchMeta) =>
420
- predicate(partialMatchMeta),
421
- );
422
- };
423
-
424
- const applyAliases = ({ url, aliases }) => {
425
- let aliasFullMatchResult;
426
- const aliasMatchingKey = Object.keys(aliases).find((key) => {
427
- const aliasMatchResult = applyPatternMatching({
428
- pattern: key,
429
- url,
430
- });
431
- if (aliasMatchResult.matched) {
432
- aliasFullMatchResult = aliasMatchResult;
433
- return true;
434
- }
435
- return false;
436
- });
437
- if (!aliasMatchingKey) {
438
- return url;
439
- }
440
- const { matchGroups } = aliasFullMatchResult;
441
- const alias = aliases[aliasMatchingKey];
442
- const parts = alias.split("*");
443
- let newUrl = "";
444
- let index = 0;
445
- for (const part of parts) {
446
- newUrl += `${part}`;
447
- if (index < parts.length - 1) {
448
- newUrl += matchGroups[index];
449
- }
450
- index++;
451
- }
452
- return newUrl;
453
- };
454
-
455
- const matches = (url, patterns) => {
456
- return Boolean(
457
- applyAssociations({
458
- url,
459
- associations: {
460
- yes: patterns,
461
- },
462
- }).yes,
463
- );
464
- };
465
-
466
- // const assertSpecifierMetaMap = (value, checkComposition = true) => {
467
- // if (!isPlainObject(value)) {
468
- // throw new TypeError(
469
- // `specifierMetaMap must be a plain object, got ${value}`,
470
- // );
471
- // }
472
- // if (checkComposition) {
473
- // const plainObject = value;
474
- // Object.keys(plainObject).forEach((key) => {
475
- // assertUrlLike(key, "specifierMetaMap key");
476
- // const value = plainObject[key];
477
- // if (value !== null && !isPlainObject(value)) {
478
- // throw new TypeError(
479
- // `specifierMetaMap value must be a plain object or null, got ${value} under key ${key}`,
480
- // );
481
- // }
482
- // });
483
- // }
484
- // };
485
- const assertUrlLike = (value, name = "url") => {
486
- if (typeof value !== "string") {
487
- throw new TypeError(`${name} must be a url string, got ${value}`);
488
- }
489
- if (isWindowsPathnameSpecifier(value)) {
490
- throw new TypeError(
491
- `${name} must be a url but looks like a windows pathname, got ${value}`,
492
- );
493
- }
494
- if (!hasScheme(value)) {
495
- throw new TypeError(
496
- `${name} must be a url and no scheme found, got ${value}`,
497
- );
498
- }
499
- };
500
- const isPlainObject = (value) => {
501
- if (value === null) {
502
- return false;
503
- }
504
- if (typeof value === "object") {
505
- if (Array.isArray(value)) {
506
- return false;
507
- }
508
- return true;
509
- }
510
- return false;
511
- };
512
- const isWindowsPathnameSpecifier = (specifier) => {
513
- const firstChar = specifier[0];
514
- if (!/[a-zA-Z]/.test(firstChar)) return false;
515
- const secondChar = specifier[1];
516
- if (secondChar !== ":") return false;
517
- const thirdChar = specifier[2];
518
- return thirdChar === "/" || thirdChar === "\\";
519
- };
520
- const hasScheme = (specifier) => /^[a-zA-Z]+:/.test(specifier);
521
-
522
- const URL_META = {
523
- resolveAssociations,
524
- applyAssociations,
525
- applyAliases,
526
- applyPatternMatching,
527
- urlChildMayMatch,
528
- matches,
529
- };
530
-
531
- function createRawFrame(raw) {
532
- return {
533
- column: -1,
534
- fileName: "",
535
- line: -1,
536
- name: "",
537
- raw: raw,
538
- sourceColumn: -1,
539
- sourceFileName: "",
540
- sourceLine: -1,
541
- type: "",
542
- };
543
- }
544
- var FIREFOX_WEBKIT = /([^@]+|^)@(.*):(\d+):(\d+)/;
545
- var WEBKIT_ADDRESS_UNNAMED = /^(http(s)?:\/\/.*):(\d+):(\d+)$/;
546
- var WEBKIT_NATIVE_UNNAMED = "[native code]";
547
- function parsWebkit(str) {
548
- if (str.includes(WEBKIT_NATIVE_UNNAMED)) {
549
- return {
550
- line: -1,
551
- column: -1,
552
- type: "native",
553
- fileName: "",
554
- name: "",
555
- raw: str,
556
- sourceColumn: -1,
557
- sourceFileName: "",
558
- sourceLine: -1,
559
- };
560
- }
561
- var match = str.match(WEBKIT_ADDRESS_UNNAMED);
562
- if (match) {
563
- var line = match[3] ? +match[3] : -1;
564
- var column = match[4] ? +match[4] : -1;
565
- var fileName = match[1] ? match[1] : "";
566
- return {
567
- line: line,
568
- column: column,
569
- type: "",
570
- fileName: fileName,
571
- name: "",
572
- raw: str,
573
- sourceColumn: -1,
574
- sourceFileName: "",
575
- sourceLine: -1,
576
- };
577
- }
578
- return createRawFrame(str);
579
- }
580
- function parseFirefoxWebkit(lines) {
581
- return lines.map(function (str) {
582
- var match = str.match(FIREFOX_WEBKIT);
583
- if (!match) {
584
- return parsWebkit(str);
585
- }
586
- var line = match[3] ? +match[3] : -1;
587
- var column = match[4] ? +match[4] : -1;
588
- var fileName = match[2] ? match[2] : "";
589
- return {
590
- line: line,
591
- column: column,
592
- type: match[0] ? "" : "native",
593
- fileName: fileName,
594
- name: (match[1] || "").trim(),
595
- raw: str,
596
- sourceColumn: -1,
597
- sourceFileName: "",
598
- sourceLine: -1,
599
- };
600
- });
601
- }
602
- // foo.bar.js:123:39
603
- // foo.bar.js:123:39 <- original.js:123:34
604
- var CHROME_MAPPED = /(.*?):(\d+):(\d+)(\s<-\s(.+):(\d+):(\d+))?/;
605
- function parseMapped(frame, maybeMapped) {
606
- var match = maybeMapped.match(CHROME_MAPPED);
607
- if (match) {
608
- frame.fileName = match[1];
609
- frame.line = +match[2];
610
- frame.column = +match[3];
611
- if (match[5])
612
- frame.sourceFileName = match[5];
613
- if (match[6])
614
- frame.sourceLine = +match[6];
615
- if (match[7])
616
- frame.sourceColumn = +match[7];
617
- }
618
- }
619
- // at <SomeFramework>
620
- var CHROME_IE_NATIVE_NO_LINE = /^at\s(<.*>)$/;
621
- // at <SomeFramework>:123:39
622
- var CHROME_IE_NATIVE = /^\s*at\s(<.*>):(\d+):(\d+)$/;
623
- // at foo.bar(bob) (foo.bar.js:123:39)
624
- // at foo.bar(bob) (foo.bar.js:123:39 <- original.js:123:34)
625
- var CHROME_IE_FUNCTION = /^at\s(.*)\s\((.*)\)$/;
626
- // >= Chrome 88
627
- // spy() at Component.Foo [as constructor] (original.js:123:34)
628
- // spy() at Component.Foo [as constructor] (foo.bar.js:123:39 <- original.js:123:34)
629
- var CHROME_IE_FUNCTION_WITH_CALL = /^([\w\W]*)\s\((.*)\)/;
630
- var CHROME_IE_DETECTOR = /\s*at\s.+/;
631
- // at about:blank:1:7
632
- // >= Chrome 99
633
- // at /projects/foo.test.js:689:1 <- /projects/foo.test.js:10:1
634
- var CHROME_BLANK = /\s*at\s(.*):(\d+):(\d+)$/;
635
- function parseChromeIe(lines) {
636
- // Many frameworks mess with error.stack. So we use this check
637
- // to find the first line of the actual stack
638
- var start = lines.findIndex(function (line) { return CHROME_IE_DETECTOR.test(line); });
639
- if (start === -1) {
640
- return [];
641
- }
642
- var frames = [];
643
- for (var i = start; i < lines.length; i++) {
644
- var str = lines[i].replace(/^\s+|\s+$/g, "");
645
- var frame = createRawFrame(lines[i]);
646
- var nativeNoLine = str.match(CHROME_IE_NATIVE_NO_LINE);
647
- if (nativeNoLine) {
648
- frame.fileName = nativeNoLine[1];
649
- frame.type = "native";
650
- frames.push(frame);
651
- continue;
652
- }
653
- var native = str.match(CHROME_IE_NATIVE);
654
- if (native) {
655
- frame.fileName = native[1];
656
- frame.type = "native";
657
- if (native[2])
658
- frame.line = +native[2];
659
- if (native[3])
660
- frame.column = +native[3];
661
- frames.push(frame);
662
- continue;
663
- }
664
- var withFn = str.match(CHROME_IE_FUNCTION);
665
- if (withFn) {
666
- frame.name = withFn[1];
667
- parseMapped(frame, withFn[2]);
668
- frames.push(frame);
669
- continue;
670
- }
671
- var blank = str.match(CHROME_BLANK);
672
- if (blank) {
673
- frame.fileName = blank[1];
674
- frame.line = +blank[2];
675
- frame.column = +blank[3];
676
- parseMapped(frame, blank[1] + ":" + blank[2] + ":" + blank[3]);
677
- frames.push(frame);
678
- continue;
679
- }
680
- var withFnCall = str.match(CHROME_IE_FUNCTION_WITH_CALL);
681
- if (withFnCall) {
682
- frame.name = withFnCall[1];
683
- parseMapped(frame, withFnCall[2]);
684
- frames.push(frame);
685
- continue;
686
- }
687
- frames.push(frame);
688
- }
689
- return frames;
690
- }
691
- function parseStackTrace(stack) {
692
- if (!stack)
693
- return [];
694
- var lines = stack.split("\n").filter(Boolean);
695
- // Libraries like node's "assert" module mess with the stack trace by
696
- // prepending custom data. So we need to do a precheck, to determine
697
- // which browser the trace is coming from.
698
- if (lines.some(function (line) { return CHROME_IE_DETECTOR.test(line); })) {
699
- return parseChromeIe(lines);
700
- }
701
- return parseFirefoxWebkit(lines);
702
- }
703
-
704
- /*
705
- * Exception are objects used to wrap a value that is thrown
706
- * Usually they wrap error but the value can be anything as
707
- * throw "toto" can be used in JS
708
- *
709
- * - provide a common API to interact with value that can be thrown
710
- * - enrich usual errors with a bit more information (line, column)
711
- * - normalize error properties
712
- * - exception.stackTrace: only the stack trace as string (no error.name or error.message)
713
- * - error.stack: error.name + error.message + error.stackTrace
714
- *
715
- * It is used mostly internally by jsenv but can also be found
716
- * value returned by "executeTestPlan" public export (for failed executions)
717
- * and value returned by "execute" public export (when execution fails)
718
- *
719
- * This file is responsible to wrap error hapenning in Node.js runtime
720
- * The browser part can be found in "supervisor.js"
721
- */
722
-
723
-
724
- const isDev = process.execArgv.includes("--conditions=development");
725
- const jsenvCoreDirectoryUrl = new URL("file:///Users/damien.maillard/dev/perso/jsenv-core/", import.meta.url);
726
-
727
- const createException = (reason, { rootDirectoryUrl } = {}) => {
728
- const exception = {
729
- isException: true,
730
- isError: false,
731
- name: "",
732
- message: "",
733
- stack: "",
734
- stackTrace: "",
735
- stackFrames: undefined,
736
- site: null,
737
- };
738
-
739
- if (reason === undefined) {
740
- exception.message = "undefined";
741
- return exception;
742
- }
743
- if (reason === null) {
744
- exception.message = "null";
745
- return exception;
746
- }
747
- if (typeof reason === "string") {
748
- exception.message = reason;
749
- return exception;
750
- }
751
- if (typeof reason !== "object") {
752
- exception.message = JSON.stringify(reason);
753
- return exception;
754
- }
755
- if (reason.stackFrames === undefined && "stack" in reason) {
756
- let stackFrames;
757
-
758
- const { prepareStackTrace } = Error;
759
- Error.prepareStackTrace = (e, callSites) => {
760
- Error.prepareStackTrace = prepareStackTrace;
761
-
762
- stackFrames = [];
763
- for (const callSite of callSites) {
764
- const stackFrame = {
765
- raw: ` at ${String(callSite)}`,
766
- url: callSite.getFileName() || callSite.getScriptNameOrSourceURL(),
767
- line: callSite.getLineNumber(),
768
- column: callSite.getColumnNumber(),
769
- functionName: callSite.getFunctionName(),
770
- isNative: callSite.isNative(),
771
- isEval: callSite.isEval(),
772
- isConstructor: callSite.isConstructor(),
773
- isAsync: callSite.isAsync(),
774
- evalSite: null,
775
- };
776
- if (stackFrame.isEval) {
777
- const evalOrigin = stackFrame.getEvalOrigin();
778
- if (evalOrigin) {
779
- stackFrame.evalSite = getPropertiesFromEvalOrigin(evalOrigin);
780
- }
781
- }
782
- stackFrames.push(stackFrame);
783
- }
784
- return "";
785
- };
786
- exception.stack = reason.stack;
787
- if (stackFrames === undefined) {
788
- // Error.prepareStackTrace not trigerred
789
- // - reason is not an error
790
- // - reason.stack already get
791
- Error.prepareStackTrace = prepareStackTrace;
792
-
793
- const calls = parseStackTrace(reason.stack);
794
- stackFrames = [];
795
- for (const call of calls) {
796
- if (call.fileName === "") {
797
- continue;
798
- }
799
- stackFrames.push({
800
- raw: call.raw,
801
- functionName: call.name,
802
- url: call.fileName,
803
- line: call.line,
804
- column: call.column,
805
- native: call.type === "native",
806
- });
807
- }
808
- }
809
-
810
- const stackFramesNonNative = [];
811
- for (const stackFrame of stackFrames) {
812
- if (!stackFrame.url) {
813
- continue;
814
- }
815
- if (stackFrame.url.startsWith("node:")) {
816
- stackFrame.native = "node";
817
- continue;
818
- }
819
- if (stackFrame.url.startsWith("file:")) {
820
- if (rootDirectoryUrl && stackFrame.url.startsWith(rootDirectoryUrl)) {
821
- stackFramesNonNative.push(stackFrame);
822
- continue;
823
- }
824
-
825
- if (isDev) {
826
- // while developing jsenv itself we want to exclude any
827
- // - src/*
828
- // - packages/**/src/
829
- // for the users of jsenv it's easier, we want to exclude
830
- // - **/node_modules/@jsenv/**
831
- if (
832
- URL_META.matches(stackFrame.url, {
833
- [`${jsenvCoreDirectoryUrl}src/`]: true,
834
- [`${jsenvCoreDirectoryUrl}packages/**/src/`]: true,
835
- })
836
- ) {
837
- stackFrame.native = "jsenv";
838
- continue;
839
- }
840
- } else if (
841
- URL_META.matches(stackFrame.url, {
842
- "file:///**/node_modules/@jsenv/core/": true,
843
- })
844
- ) {
845
- stackFrame.native = "jsenv";
846
- continue;
847
- }
848
- }
849
- stackFramesNonNative.push(stackFrame);
850
- }
851
- if (stackFramesNonNative.length) {
852
- stackFrames = stackFramesNonNative;
853
- }
854
-
855
- reason.stackFrames = stackFrames;
856
-
857
- let stackTrace = "";
858
- for (const stackFrame of stackFrames) {
859
- if (stackTrace) stackTrace += "\n";
860
- stackTrace += stackFrame.raw;
861
- }
862
- reason.stackTrace = stackTrace;
863
- let stack = "";
864
- const name = getErrorName(reason);
865
- const message = reason.message || "";
866
- stack += `${name}: ${message}`;
867
- if (stackTrace) {
868
- stack += `\n${stackTrace}`;
869
- }
870
- reason.stack = stack;
871
-
872
- const [firstCallFrame] = stackFrames;
873
- if (firstCallFrame && (!reason.site || !reason.site.isInline)) {
874
- reason.site = firstCallFrame.url
875
- ? {
876
- url: firstCallFrame.url,
877
- line: firstCallFrame.line,
878
- column: firstCallFrame.column,
879
- }
880
- : firstCallFrame.evalSite;
881
- }
882
- }
883
- // getOwnPropertyNames to catch non enumerable properties on reason
884
- // (happens mostly when reason is instanceof Error)
885
- // like .stack, .message
886
- // some properties are even on the prototype like .name
887
- for (const ownPropertyName of Object.getOwnPropertyNames(reason)) {
888
- exception[ownPropertyName] = reason[ownPropertyName];
889
- }
890
- const isError = reason instanceof Error;
891
- exception.isError = isError;
892
- if (isError) {
893
- // getOwnPropertyNames is not enough to copy .name and .message
894
- // on error instances
895
- exception.name = getErrorName(reason);
896
- exception.message = reason.message;
897
- }
898
- return exception;
899
- };
900
-
901
- const getErrorName = (value) => {
902
- const { constructor } = value;
903
- if (constructor) {
904
- if (constructor.name !== "Object") {
905
- return constructor.name;
906
- }
907
- }
908
- return value.name || "Error";
909
- };
910
-
911
- const getPropertiesFromEvalOrigin = (origin) => {
912
- // Most eval() calls are in this format
913
- const topLevelEvalMatch = /^eval at [^(]+ \(.+:\d+:\d+\)$/.exec(origin);
914
- if (topLevelEvalMatch) {
915
- const source = topLevelEvalMatch[2];
916
- const line = Number(topLevelEvalMatch[3]);
917
- const column = topLevelEvalMatch[4] - 1;
918
- return {
919
- url: source,
920
- line,
921
- column,
922
- };
923
- }
924
- // Parse nested eval() calls using recursion
925
- const nestedEvalMatch = /^eval at [^(]+ \(.+\)$/.exec(origin);
926
- if (nestedEvalMatch) {
927
- return getPropertiesFromEvalOrigin(nestedEvalMatch[2]);
928
- }
929
- return null;
930
- };
931
-
932
- export { URL_META, createException };