@vitest/utils 4.1.0-beta.2 → 4.1.0-beta.4

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/diff.js CHANGED
@@ -2,7 +2,6 @@ import { plugins, format } from '@vitest/pretty-format';
2
2
  import c from 'tinyrainbow';
3
3
  import { stringify } from './display.js';
4
4
  import { deepClone, getOwnProperties, getType as getType$1 } from './helpers.js';
5
- import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js';
6
5
  import './constants.js';
7
6
 
8
7
  /**
@@ -333,7 +332,6 @@ function diff_cleanupSemanticLossless(diffs) {
333
332
  * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
334
333
  */
335
334
  function diff_cleanupMerge(diffs) {
336
- var _diffs$at;
337
335
  // Add a dummy entry at the end.
338
336
  diffs.push(new Diff(DIFF_EQUAL, ""));
339
337
  let pointer = 0;
@@ -404,7 +402,7 @@ function diff_cleanupMerge(diffs) {
404
402
  break;
405
403
  }
406
404
  }
407
- if (((_diffs$at = diffs.at(-1)) === null || _diffs$at === void 0 ? void 0 : _diffs$at[1]) === "") {
405
+ if (diffs.at(-1)?.[1] === "") {
408
406
  diffs.pop();
409
407
  }
410
408
  // Second pass: look for single edits surrounded on both sides by equalities
@@ -495,6 +493,10 @@ function diff_cleanupSemanticScore_(one, two) {
495
493
  const NO_DIFF_MESSAGE = "Compared values have no visual difference.";
496
494
  const SIMILAR_MESSAGE = "Compared values serialize to the same structure.\n" + "Printing internal object structure without calling `toJSON` instead.";
497
495
 
496
+ function getDefaultExportFromCjs(x) {
497
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
498
+ }
499
+
498
500
  var build = {};
499
501
 
500
502
  var hasRequiredBuild;
@@ -1623,8 +1625,8 @@ function diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCo
1623
1625
  }
1624
1626
  // Compare two arrays of strings line-by-line.
1625
1627
  function diffLinesRaw(aLines, bLines, options) {
1626
- const truncate = (options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? false;
1627
- const truncateThreshold = Math.max(Math.floor((options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? 0), 0);
1628
+ const truncate = options?.truncateThreshold ?? false;
1629
+ const truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0);
1628
1630
  const aLength = truncate ? Math.min(aLines.length, truncateThreshold) : aLines.length;
1629
1631
  const bLength = truncate ? Math.min(bLines.length, truncateThreshold) : bLines.length;
1630
1632
  const truncated = aLength !== aLines.length || bLength !== bLines.length;
@@ -1697,8 +1699,8 @@ function getNewLineSymbol(string) {
1697
1699
  return string.includes("\r\n") ? "\r\n" : "\n";
1698
1700
  }
1699
1701
  function diffStrings(a, b, options) {
1700
- const truncate = (options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? false;
1701
- const truncateThreshold = Math.max(Math.floor((options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? 0), 0);
1702
+ const truncate = options?.truncateThreshold ?? false;
1703
+ const truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0);
1702
1704
  let aLength = a.length;
1703
1705
  let bLength = b.length;
1704
1706
  if (truncate) {
package/dist/display.js CHANGED
@@ -694,6 +694,9 @@ function baseFormat(args, options = {}) {
694
694
  if (typeof value === "bigint") {
695
695
  return `${value.toString()}n`;
696
696
  }
697
+ if (typeof value === "symbol") {
698
+ return "NaN";
699
+ }
697
700
  return Number(value).toString();
698
701
  }
699
702
  case "%i": {
@@ -727,7 +730,7 @@ function baseFormat(args, options = {}) {
727
730
  });
728
731
  for (let x = args[i]; i < len; x = args[++i]) {
729
732
  if (x === null || typeof x !== "object") {
730
- str += ` ${x}`;
733
+ str += ` ${typeof x === "symbol" ? x.toString() : x}`;
731
734
  } else {
732
735
  str += ` ${formatArg(x)}`;
733
736
  }
package/dist/error.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { D as DiffOptions } from './types.d-BCElaP-c.js';
2
+ import { TestError } from './types.js';
2
3
  export { serializeValue as serializeError } from './serialize.js';
3
4
  import '@vitest/pretty-format';
4
5
 
5
- declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet<WeakKey>): any;
6
+ declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet<WeakKey>): TestError;
6
7
 
7
8
  export { processError };
package/dist/error.js CHANGED
@@ -5,7 +5,6 @@ import '@vitest/pretty-format';
5
5
  import 'tinyrainbow';
6
6
  import './helpers.js';
7
7
  import './constants.js';
8
- import './chunk-_commonjsHelpers.js';
9
8
 
10
9
  function processError(_err, diffOptions, seen = new WeakSet()) {
11
10
  if (!_err || typeof _err !== "object") {
@@ -35,7 +34,7 @@ function processError(_err, diffOptions, seen = new WeakSet()) {
35
34
  try {
36
35
  return serializeValue(err);
37
36
  } catch (e) {
38
- return serializeValue(new Error(`Failed to fully serialize error: ${e === null || e === void 0 ? void 0 : e.message}\nInner error message: ${err === null || err === void 0 ? void 0 : err.message}`));
37
+ return serializeValue(new Error(`Failed to fully serialize error: ${e?.message}\nInner error message: ${err?.message}`));
39
38
  }
40
39
  }
41
40
 
package/dist/resolver.js CHANGED
@@ -5,13 +5,12 @@ const packageCache = new Map();
5
5
  function findNearestPackageData(basedir) {
6
6
  const originalBasedir = basedir;
7
7
  while (basedir) {
8
- var _tryStatSync;
9
8
  const cached = getCachedData(packageCache, basedir, originalBasedir);
10
9
  if (cached) {
11
10
  return cached;
12
11
  }
13
12
  const pkgPath = join(basedir, "package.json");
14
- if ((_tryStatSync = tryStatSync(pkgPath)) === null || _tryStatSync === void 0 ? void 0 : _tryStatSync.isFile()) {
13
+ if (tryStatSync(pkgPath)?.isFile()) {
15
14
  const pkgData = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf8")));
16
15
  if (packageCache) {
17
16
  setCacheData(packageCache, pkgData, basedir, originalBasedir);
package/dist/serialize.js CHANGED
@@ -22,16 +22,16 @@ function serializeValue(val, seen = new WeakMap()) {
22
22
  const jsonValue = val.toJSON();
23
23
  if (jsonValue && jsonValue !== val && typeof jsonValue === "object") {
24
24
  if (typeof val.message === "string") {
25
- safe(() => jsonValue.message ?? (jsonValue.message = normalizeErrorMessage(val.message)));
25
+ safe(() => jsonValue.message ??= normalizeErrorMessage(val.message));
26
26
  }
27
27
  if (typeof val.stack === "string") {
28
- safe(() => jsonValue.stack ?? (jsonValue.stack = val.stack));
28
+ safe(() => jsonValue.stack ??= val.stack);
29
29
  }
30
30
  if (typeof val.name === "string") {
31
- safe(() => jsonValue.name ?? (jsonValue.name = val.name));
31
+ safe(() => jsonValue.name ??= val.name);
32
32
  }
33
33
  if (val.cause != null) {
34
- safe(() => jsonValue.cause ?? (jsonValue.cause = serializeValue(val.cause, seen)));
34
+ safe(() => jsonValue.cause ??= serializeValue(val.cause, seen));
35
35
  }
36
36
  }
37
37
  return serializeValue(jsonValue, seen);
@@ -101,7 +101,7 @@ function serializeValue(val, seen = new WeakMap()) {
101
101
  obj = Object.getPrototypeOf(obj);
102
102
  }
103
103
  if (val instanceof Error) {
104
- safe(() => val.message = normalizeErrorMessage(val.message));
104
+ safe(() => clone.message = normalizeErrorMessage(val.message));
105
105
  }
106
106
  return clone;
107
107
  }
@@ -112,7 +112,7 @@ function safe(fn) {
112
112
  } catch {}
113
113
  }
114
114
  function normalizeErrorMessage(message) {
115
- return message.replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "");
115
+ return message.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/getByTestId('__vitest_\d+__')/g, "page");
116
116
  }
117
117
 
118
118
  export { serializeValue };
@@ -233,6 +233,7 @@ const stackIgnorePatterns = [
233
233
  /node:\w+/,
234
234
  /__vitest_test__/,
235
235
  /__vitest_browser__/,
236
+ "/@id/__x00__vitest/browser",
236
237
  /\/deps\/vitest_/
237
238
  ];
238
239
  const NOW_LENGTH = Date.now().toString().length;
@@ -357,7 +358,7 @@ function parseSingleV8Stack(raw) {
357
358
  // normalize Windows path (\ -> /)
358
359
  file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
359
360
  if (method) {
360
- method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
361
+ method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
361
362
  }
362
363
  return {
363
364
  method,
@@ -377,13 +378,17 @@ function createStackString(stacks) {
377
378
  }
378
379
  function parseStacktrace(stack, options = {}) {
379
380
  const { ignoreStackEntries = stackIgnorePatterns } = options;
380
- const stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
381
+ let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
382
+ // remove assertion helper's internal stacks
383
+ const helperIndex = stacks.findLastIndex((s) => s.method === "__VITEST_HELPER__" || s.method === "async*__VITEST_HELPER__");
384
+ if (helperIndex >= 0) {
385
+ stacks = stacks.slice(helperIndex + 1);
386
+ }
381
387
  return stacks.map((stack) => {
382
- var _options$getSourceMap;
383
388
  if (options.getUrlId) {
384
389
  stack.file = options.getUrlId(stack.file);
385
390
  }
386
- const map = (_options$getSourceMap = options.getSourceMap) === null || _options$getSourceMap === void 0 ? void 0 : _options$getSourceMap.call(options, stack.file);
391
+ const map = options.getSourceMap?.(stack.file);
387
392
  if (!map || typeof map !== "object" || !map.version) {
388
393
  return shouldFilter(ignoreStackEntries, stack.file) ? null : stack;
389
394
  }
@@ -462,7 +467,7 @@ class DecodedMap {
462
467
  this._encoded = mappings || "";
463
468
  this._decodedMemo = memoizedState();
464
469
  this.url = from;
465
- this.resolvedSources = (sources || []).map((s) => resolve(s || "", from));
470
+ this.resolvedSources = (sources || []).map((s) => resolve(from, "..", s || ""));
466
471
  }
467
472
  }
468
473
  function memoizedState() {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vitest/utils",
3
3
  "type": "module",
4
- "version": "4.1.0-beta.2",
4
+ "version": "4.1.0-beta.4",
5
5
  "description": "Shared Vitest utility functions",
6
6
  "license": "MIT",
7
7
  "funding": "https://opencollective.com/vitest",
@@ -52,10 +52,6 @@
52
52
  "types": "./dist/display.d.ts",
53
53
  "default": "./dist/display.js"
54
54
  },
55
- "./highlight": {
56
- "types": "./dist/highlight.d.ts",
57
- "default": "./dist/highlight.js"
58
- },
59
55
  "./source-map": {
60
56
  "types": "./dist/source-map.d.ts",
61
57
  "default": "./dist/source-map.js"
@@ -82,14 +78,13 @@
82
78
  ],
83
79
  "dependencies": {
84
80
  "tinyrainbow": "^3.0.3",
85
- "@vitest/pretty-format": "4.1.0-beta.2"
81
+ "@vitest/pretty-format": "4.1.0-beta.4"
86
82
  },
87
83
  "devDependencies": {
88
84
  "@jridgewell/trace-mapping": "0.3.31",
89
85
  "@types/estree": "^1.0.8",
90
86
  "diff-sequences": "^29.6.3",
91
- "loupe": "^3.2.1",
92
- "tinyhighlight": "^0.3.2"
87
+ "loupe": "^3.2.1"
93
88
  },
94
89
  "scripts": {
95
90
  "build": "premove dist && rollup -c",
@@ -1,5 +0,0 @@
1
- function getDefaultExportFromCjs(x) {
2
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
3
- }
4
-
5
- export { getDefaultExportFromCjs as g };
@@ -1,9 +0,0 @@
1
- import { Colors } from 'tinyrainbow';
2
-
3
- interface HighlightOptions {
4
- jsx?: boolean;
5
- colors?: Colors;
6
- }
7
- declare function highlight(code: string, options?: HighlightOptions): string;
8
-
9
- export { highlight };
package/dist/highlight.js DELETED
@@ -1,538 +0,0 @@
1
- import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js';
2
- import c from 'tinyrainbow';
3
-
4
- var jsTokens_1;
5
- var hasRequiredJsTokens;
6
-
7
- function requireJsTokens () {
8
- if (hasRequiredJsTokens) return jsTokens_1;
9
- hasRequiredJsTokens = 1;
10
- // Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell
11
- // License: MIT.
12
- var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
13
- RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\\]).|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
14
- Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
15
- Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
16
- StringLiteral = /(['"])(?:(?!\1)[^\\\n\r]|\\(?:\r\n|[^]))*(\1)?/y;
17
- NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
18
- Template = /[`}](?:[^`\\$]|\\[^]|\$(?!\{))*(`|\$\{)?/y;
19
- WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
20
- LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
21
- MultiLineComment = /\/\*(?:[^*]|\*(?!\/))*(\*\/)?/y;
22
- SingleLineComment = /\/\/.*/y;
23
- JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
24
- JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
25
- JSXString = /(['"])(?:(?!\1)[^])*(\1)?/y;
26
- JSXText = /[^<>{}]+/y;
27
- TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
28
- TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
29
- KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
30
- KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
31
- Newline = RegExp(LineTerminatorSequence.source);
32
- jsTokens_1 = function*(input, {jsx = false} = {}) {
33
- var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
34
- ({length} = input);
35
- lastIndex = 0;
36
- lastSignificantToken = "";
37
- stack = [
38
- {tag: "JS"}
39
- ];
40
- braces = [];
41
- parenNesting = 0;
42
- postfixIncDec = false;
43
- while (lastIndex < length) {
44
- mode = stack[stack.length - 1];
45
- switch (mode.tag) {
46
- case "JS":
47
- case "JSNonExpressionParen":
48
- case "InterpolationInTemplate":
49
- case "InterpolationInJSX":
50
- if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
51
- RegularExpressionLiteral.lastIndex = lastIndex;
52
- if (match = RegularExpressionLiteral.exec(input)) {
53
- lastIndex = RegularExpressionLiteral.lastIndex;
54
- lastSignificantToken = match[0];
55
- postfixIncDec = true;
56
- yield ({
57
- type: "RegularExpressionLiteral",
58
- value: match[0],
59
- closed: match[1] !== void 0 && match[1] !== "\\"
60
- });
61
- continue;
62
- }
63
- }
64
- Punctuator.lastIndex = lastIndex;
65
- if (match = Punctuator.exec(input)) {
66
- punctuator = match[0];
67
- nextLastIndex = Punctuator.lastIndex;
68
- nextLastSignificantToken = punctuator;
69
- switch (punctuator) {
70
- case "(":
71
- if (lastSignificantToken === "?NonExpressionParenKeyword") {
72
- stack.push({
73
- tag: "JSNonExpressionParen",
74
- nesting: parenNesting
75
- });
76
- }
77
- parenNesting++;
78
- postfixIncDec = false;
79
- break;
80
- case ")":
81
- parenNesting--;
82
- postfixIncDec = true;
83
- if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
84
- stack.pop();
85
- nextLastSignificantToken = "?NonExpressionParenEnd";
86
- postfixIncDec = false;
87
- }
88
- break;
89
- case "{":
90
- Punctuator.lastIndex = 0;
91
- isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
92
- braces.push(isExpression);
93
- postfixIncDec = false;
94
- break;
95
- case "}":
96
- switch (mode.tag) {
97
- case "InterpolationInTemplate":
98
- if (braces.length === mode.nesting) {
99
- Template.lastIndex = lastIndex;
100
- match = Template.exec(input);
101
- lastIndex = Template.lastIndex;
102
- lastSignificantToken = match[0];
103
- if (match[1] === "${") {
104
- lastSignificantToken = "?InterpolationInTemplate";
105
- postfixIncDec = false;
106
- yield ({
107
- type: "TemplateMiddle",
108
- value: match[0]
109
- });
110
- } else {
111
- stack.pop();
112
- postfixIncDec = true;
113
- yield ({
114
- type: "TemplateTail",
115
- value: match[0],
116
- closed: match[1] === "`"
117
- });
118
- }
119
- continue;
120
- }
121
- break;
122
- case "InterpolationInJSX":
123
- if (braces.length === mode.nesting) {
124
- stack.pop();
125
- lastIndex += 1;
126
- lastSignificantToken = "}";
127
- yield ({
128
- type: "JSXPunctuator",
129
- value: "}"
130
- });
131
- continue;
132
- }
133
- }
134
- postfixIncDec = braces.pop();
135
- nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
136
- break;
137
- case "]":
138
- postfixIncDec = true;
139
- break;
140
- case "++":
141
- case "--":
142
- nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
143
- break;
144
- case "<":
145
- if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
146
- stack.push({tag: "JSXTag"});
147
- lastIndex += 1;
148
- lastSignificantToken = "<";
149
- yield ({
150
- type: "JSXPunctuator",
151
- value: punctuator
152
- });
153
- continue;
154
- }
155
- postfixIncDec = false;
156
- break;
157
- default:
158
- postfixIncDec = false;
159
- }
160
- lastIndex = nextLastIndex;
161
- lastSignificantToken = nextLastSignificantToken;
162
- yield ({
163
- type: "Punctuator",
164
- value: punctuator
165
- });
166
- continue;
167
- }
168
- Identifier.lastIndex = lastIndex;
169
- if (match = Identifier.exec(input)) {
170
- lastIndex = Identifier.lastIndex;
171
- nextLastSignificantToken = match[0];
172
- switch (match[0]) {
173
- case "for":
174
- case "if":
175
- case "while":
176
- case "with":
177
- if (lastSignificantToken !== "." && lastSignificantToken !== "?.") {
178
- nextLastSignificantToken = "?NonExpressionParenKeyword";
179
- }
180
- }
181
- lastSignificantToken = nextLastSignificantToken;
182
- postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
183
- yield ({
184
- type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
185
- value: match[0]
186
- });
187
- continue;
188
- }
189
- StringLiteral.lastIndex = lastIndex;
190
- if (match = StringLiteral.exec(input)) {
191
- lastIndex = StringLiteral.lastIndex;
192
- lastSignificantToken = match[0];
193
- postfixIncDec = true;
194
- yield ({
195
- type: "StringLiteral",
196
- value: match[0],
197
- closed: match[2] !== void 0
198
- });
199
- continue;
200
- }
201
- NumericLiteral.lastIndex = lastIndex;
202
- if (match = NumericLiteral.exec(input)) {
203
- lastIndex = NumericLiteral.lastIndex;
204
- lastSignificantToken = match[0];
205
- postfixIncDec = true;
206
- yield ({
207
- type: "NumericLiteral",
208
- value: match[0]
209
- });
210
- continue;
211
- }
212
- Template.lastIndex = lastIndex;
213
- if (match = Template.exec(input)) {
214
- lastIndex = Template.lastIndex;
215
- lastSignificantToken = match[0];
216
- if (match[1] === "${") {
217
- lastSignificantToken = "?InterpolationInTemplate";
218
- stack.push({
219
- tag: "InterpolationInTemplate",
220
- nesting: braces.length
221
- });
222
- postfixIncDec = false;
223
- yield ({
224
- type: "TemplateHead",
225
- value: match[0]
226
- });
227
- } else {
228
- postfixIncDec = true;
229
- yield ({
230
- type: "NoSubstitutionTemplate",
231
- value: match[0],
232
- closed: match[1] === "`"
233
- });
234
- }
235
- continue;
236
- }
237
- break;
238
- case "JSXTag":
239
- case "JSXTagEnd":
240
- JSXPunctuator.lastIndex = lastIndex;
241
- if (match = JSXPunctuator.exec(input)) {
242
- lastIndex = JSXPunctuator.lastIndex;
243
- nextLastSignificantToken = match[0];
244
- switch (match[0]) {
245
- case "<":
246
- stack.push({tag: "JSXTag"});
247
- break;
248
- case ">":
249
- stack.pop();
250
- if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
251
- nextLastSignificantToken = "?JSX";
252
- postfixIncDec = true;
253
- } else {
254
- stack.push({tag: "JSXChildren"});
255
- }
256
- break;
257
- case "{":
258
- stack.push({
259
- tag: "InterpolationInJSX",
260
- nesting: braces.length
261
- });
262
- nextLastSignificantToken = "?InterpolationInJSX";
263
- postfixIncDec = false;
264
- break;
265
- case "/":
266
- if (lastSignificantToken === "<") {
267
- stack.pop();
268
- if (stack[stack.length - 1].tag === "JSXChildren") {
269
- stack.pop();
270
- }
271
- stack.push({tag: "JSXTagEnd"});
272
- }
273
- }
274
- lastSignificantToken = nextLastSignificantToken;
275
- yield ({
276
- type: "JSXPunctuator",
277
- value: match[0]
278
- });
279
- continue;
280
- }
281
- JSXIdentifier.lastIndex = lastIndex;
282
- if (match = JSXIdentifier.exec(input)) {
283
- lastIndex = JSXIdentifier.lastIndex;
284
- lastSignificantToken = match[0];
285
- yield ({
286
- type: "JSXIdentifier",
287
- value: match[0]
288
- });
289
- continue;
290
- }
291
- JSXString.lastIndex = lastIndex;
292
- if (match = JSXString.exec(input)) {
293
- lastIndex = JSXString.lastIndex;
294
- lastSignificantToken = match[0];
295
- yield ({
296
- type: "JSXString",
297
- value: match[0],
298
- closed: match[2] !== void 0
299
- });
300
- continue;
301
- }
302
- break;
303
- case "JSXChildren":
304
- JSXText.lastIndex = lastIndex;
305
- if (match = JSXText.exec(input)) {
306
- lastIndex = JSXText.lastIndex;
307
- lastSignificantToken = match[0];
308
- yield ({
309
- type: "JSXText",
310
- value: match[0]
311
- });
312
- continue;
313
- }
314
- switch (input[lastIndex]) {
315
- case "<":
316
- stack.push({tag: "JSXTag"});
317
- lastIndex++;
318
- lastSignificantToken = "<";
319
- yield ({
320
- type: "JSXPunctuator",
321
- value: "<"
322
- });
323
- continue;
324
- case "{":
325
- stack.push({
326
- tag: "InterpolationInJSX",
327
- nesting: braces.length
328
- });
329
- lastIndex++;
330
- lastSignificantToken = "?InterpolationInJSX";
331
- postfixIncDec = false;
332
- yield ({
333
- type: "JSXPunctuator",
334
- value: "{"
335
- });
336
- continue;
337
- }
338
- }
339
- WhiteSpace.lastIndex = lastIndex;
340
- if (match = WhiteSpace.exec(input)) {
341
- lastIndex = WhiteSpace.lastIndex;
342
- yield ({
343
- type: "WhiteSpace",
344
- value: match[0]
345
- });
346
- continue;
347
- }
348
- LineTerminatorSequence.lastIndex = lastIndex;
349
- if (match = LineTerminatorSequence.exec(input)) {
350
- lastIndex = LineTerminatorSequence.lastIndex;
351
- postfixIncDec = false;
352
- if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
353
- lastSignificantToken = "?NoLineTerminatorHere";
354
- }
355
- yield ({
356
- type: "LineTerminatorSequence",
357
- value: match[0]
358
- });
359
- continue;
360
- }
361
- MultiLineComment.lastIndex = lastIndex;
362
- if (match = MultiLineComment.exec(input)) {
363
- lastIndex = MultiLineComment.lastIndex;
364
- if (Newline.test(match[0])) {
365
- postfixIncDec = false;
366
- if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
367
- lastSignificantToken = "?NoLineTerminatorHere";
368
- }
369
- }
370
- yield ({
371
- type: "MultiLineComment",
372
- value: match[0],
373
- closed: match[1] !== void 0
374
- });
375
- continue;
376
- }
377
- SingleLineComment.lastIndex = lastIndex;
378
- if (match = SingleLineComment.exec(input)) {
379
- lastIndex = SingleLineComment.lastIndex;
380
- postfixIncDec = false;
381
- yield ({
382
- type: "SingleLineComment",
383
- value: match[0]
384
- });
385
- continue;
386
- }
387
- firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
388
- lastIndex += firstCodePoint.length;
389
- lastSignificantToken = firstCodePoint;
390
- postfixIncDec = false;
391
- yield ({
392
- type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
393
- value: firstCodePoint
394
- });
395
- }
396
- return void 0;
397
- };
398
- return jsTokens_1;
399
- }
400
-
401
- var jsTokensExports = /*@__PURE__*/ requireJsTokens();
402
- var jsTokens = /*@__PURE__*/getDefaultExportFromCjs(jsTokensExports);
403
-
404
- // src/index.ts
405
- var reservedWords = {
406
- keyword: [
407
- "break",
408
- "case",
409
- "catch",
410
- "continue",
411
- "debugger",
412
- "default",
413
- "do",
414
- "else",
415
- "finally",
416
- "for",
417
- "function",
418
- "if",
419
- "return",
420
- "switch",
421
- "throw",
422
- "try",
423
- "var",
424
- "const",
425
- "while",
426
- "with",
427
- "new",
428
- "this",
429
- "super",
430
- "class",
431
- "extends",
432
- "export",
433
- "import",
434
- "null",
435
- "true",
436
- "false",
437
- "in",
438
- "instanceof",
439
- "typeof",
440
- "void",
441
- "delete"
442
- ],
443
- strict: [
444
- "implements",
445
- "interface",
446
- "let",
447
- "package",
448
- "private",
449
- "protected",
450
- "public",
451
- "static",
452
- "yield"
453
- ]
454
- }, keywords = new Set(reservedWords.keyword), reservedWordsStrictSet = new Set(reservedWords.strict), sometimesKeywords = /* @__PURE__ */ new Set(["as", "async", "from", "get", "of", "set"]);
455
- function isReservedWord(word) {
456
- return word === "await" || word === "enum";
457
- }
458
- function isStrictReservedWord(word) {
459
- return isReservedWord(word) || reservedWordsStrictSet.has(word);
460
- }
461
- function isKeyword(word) {
462
- return keywords.has(word);
463
- }
464
- var BRACKET = /^[()[\]{}]$/, getTokenType = function(token) {
465
- if (token.type === "IdentifierName") {
466
- if (isKeyword(token.value) || isStrictReservedWord(token.value) || sometimesKeywords.has(token.value))
467
- return "Keyword";
468
- if (token.value[0] && token.value[0] !== token.value[0].toLowerCase())
469
- return "IdentifierCapitalized";
470
- }
471
- return token.type === "Punctuator" && BRACKET.test(token.value) ? "Bracket" : token.type === "Invalid" && (token.value === "@" || token.value === "#") ? "Punctuator" : token.type;
472
- };
473
- function getCallableType(token) {
474
- if (token.type === "IdentifierName")
475
- return "IdentifierCallable";
476
- if (token.type === "PrivateIdentifier")
477
- return "PrivateIdentifierCallable";
478
- throw new Error("Not a callable token");
479
- }
480
- var colorize = (defs, type, value) => {
481
- let colorize2 = defs[type];
482
- return colorize2 ? colorize2(value) : value;
483
- }, highlightTokens = (defs, text, jsx) => {
484
- let highlighted = "", lastPotentialCallable = null, stackedHighlight = "";
485
- for (let token of jsTokens(text, { jsx })) {
486
- let type = getTokenType(token);
487
- if (type === "IdentifierName" || type === "PrivateIdentifier") {
488
- lastPotentialCallable && (highlighted += colorize(defs, getTokenType(lastPotentialCallable), lastPotentialCallable.value) + stackedHighlight, stackedHighlight = ""), lastPotentialCallable = token;
489
- continue;
490
- }
491
- if (lastPotentialCallable && (token.type === "WhiteSpace" || token.type === "LineTerminatorSequence" || token.type === "Punctuator" && (token.value === "?." || token.value === "!"))) {
492
- stackedHighlight += colorize(defs, type, token.value);
493
- continue;
494
- }
495
- if (stackedHighlight && !lastPotentialCallable && (highlighted += stackedHighlight, stackedHighlight = ""), lastPotentialCallable) {
496
- let type2 = token.type === "Punctuator" && token.value === "(" ? getCallableType(lastPotentialCallable) : getTokenType(lastPotentialCallable);
497
- highlighted += colorize(defs, type2, lastPotentialCallable.value) + stackedHighlight, stackedHighlight = "", lastPotentialCallable = null;
498
- }
499
- highlighted += colorize(defs, type, token.value);
500
- }
501
- return highlighted;
502
- };
503
- function highlight$1(code, options = { jsx: false, colors: {} }) {
504
- return code && highlightTokens(options.colors || {}, code, options.jsx);
505
- }
506
-
507
- function getDefs(c) {
508
- const Invalid = (text) => c.white(c.bgRed(c.bold(text)));
509
- return {
510
- Keyword: c.magenta,
511
- IdentifierCapitalized: c.yellow,
512
- Punctuator: c.yellow,
513
- StringLiteral: c.green,
514
- NoSubstitutionTemplate: c.green,
515
- MultiLineComment: c.gray,
516
- SingleLineComment: c.gray,
517
- RegularExpressionLiteral: c.cyan,
518
- NumericLiteral: c.blue,
519
- TemplateHead: (text) => c.green(text.slice(0, text.length - 2)) + c.cyan(text.slice(-2)),
520
- TemplateTail: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1)),
521
- TemplateMiddle: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1, text.length - 2)) + c.cyan(text.slice(-2)),
522
- IdentifierCallable: c.blue,
523
- PrivateIdentifierCallable: (text) => `#${c.blue(text.slice(1))}`,
524
- Invalid,
525
- JSXString: c.green,
526
- JSXIdentifier: c.yellow,
527
- JSXInvalid: Invalid,
528
- JSXPunctuator: c.yellow
529
- };
530
- }
531
- function highlight(code, options = { jsx: false }) {
532
- return highlight$1(code, {
533
- jsx: options.jsx,
534
- colors: getDefs(options.colors || c)
535
- });
536
- }
537
-
538
- export { highlight };