@remotex-labs/xmap 1.0.4 → 2.0.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.
Files changed (35) hide show
  1. package/README.md +206 -143
  2. package/dist/{components → cjs/components}/formatter.component.d.ts +3 -3
  3. package/dist/{components → cjs/components}/highlighter.component.d.ts +1 -1
  4. package/dist/{components → cjs/components}/parser.component.d.ts +1 -1
  5. package/dist/cjs/index.d.ts +9 -0
  6. package/dist/cjs/index.js +7 -0
  7. package/dist/cjs/index.js.map +8 -0
  8. package/dist/cjs/providers/interfaces/mapping.interface.d.ts +52 -0
  9. package/dist/cjs/providers/mapping.provider.d.ts +229 -0
  10. package/dist/cjs/services/interfaces/source.interface.d.ts +53 -0
  11. package/dist/cjs/services/source.service.d.ts +217 -0
  12. package/dist/esm/components/base64.component.d.ts +26 -0
  13. package/dist/esm/components/formatter.component.d.ts +66 -0
  14. package/dist/esm/components/highlighter.component.d.ts +186 -0
  15. package/dist/esm/components/interfaces/formatter.interface.d.ts +42 -0
  16. package/dist/esm/components/interfaces/highlighter.interface.d.ts +48 -0
  17. package/dist/esm/components/interfaces/parse.interface.d.ts +31 -0
  18. package/dist/esm/components/parser.component.d.ts +11 -0
  19. package/dist/esm/index.d.ts +9 -0
  20. package/dist/esm/index.js +7 -0
  21. package/dist/esm/index.js.map +8 -0
  22. package/dist/esm/providers/interfaces/mapping.interface.d.ts +52 -0
  23. package/dist/esm/providers/mapping.provider.d.ts +229 -0
  24. package/dist/esm/services/interfaces/source.interface.d.ts +53 -0
  25. package/dist/esm/services/source.service.d.ts +217 -0
  26. package/package.json +27 -12
  27. package/dist/index.d.ts +0 -9
  28. package/dist/index.js +0 -9
  29. package/dist/index.js.map +0 -7
  30. package/dist/services/interfaces/source.interface.d.ts +0 -252
  31. package/dist/services/source.service.d.ts +0 -399
  32. /package/dist/{components → cjs/components}/base64.component.d.ts +0 -0
  33. /package/dist/{components → cjs/components}/interfaces/formatter.interface.d.ts +0 -0
  34. /package/dist/{components → cjs/components}/interfaces/highlighter.interface.d.ts +0 -0
  35. /package/dist/{components → cjs/components}/interfaces/parse.interface.d.ts +0 -0
package/README.md CHANGED
@@ -1,143 +1,206 @@
1
- # xMap
2
- ## Description
3
- `xMap` is a library designed to help with sourcemap parsing and TypeScript code formatting for the CLI.\
4
- It includes components for parsing error stack traces, formatting code, and providing syntax highlighting, as well as a service for handling source maps.
5
-
6
- ## Installation
7
- To install the package, use npm or yarn:
8
- ```bash
9
- npm install @remotex-labs/xmap
10
- ```
11
- or
12
- ```bash
13
- yarn add @remotex-labs/xmap
14
- ```
15
- ## Usage
16
- ### Parsing Error Stack Traces
17
- The parseErrorStack function parses an error stack trace and returns an array of stack entries.\
18
- Each entry contains information about the function call, file, line number, column number, and if applicable, details about the eval context.
19
-
20
- **Example**
21
- ```typescript
22
- import { parseErrorStack } from '@remotex-labs/xmap';
23
-
24
- // Example stack trace string
25
- const stackTrace = `
26
- Error: Example error
27
- at Object.<anonymous> (/path/to/file.js:10:15)
28
- at Module._compile (node:internal/modules/cjs/loader:1217:14)
29
- at node:internal/modules/cjs/loader:1308:14
30
- at node:internal/modules/cjs/loader:1425:5
31
- at node:internal/modules/cjs/loader:1425:5
32
- at node:internal/modules/cjs/loader:1483:3
33
- at node:internal/modules/cjs/loader:1700:8
34
- at node:internal/modules/cjs/loader:1760:3
35
- at /path/to/file.js:10:15
36
- at Object.<anonymous> (/path/to/file.js:10:15)
37
- at eval (eval at <anonymous> (/path/to/file.js:10:15), <anonymous>:1:1)
38
- `;
39
-
40
- // Parsing the stack trace
41
- const parsedStack = parseErrorStack(stackTrace);
42
- console.log(parsedStack);
43
- ```
44
-
45
- ### Formatting Code
46
- The formatCode function formats a code snippet with optional line padding and custom actions.\
47
- It applies padding to line numbers and can trigger custom actions for specific lines.
48
-
49
- Function Signature
50
- ```typescript
51
- export function formatCode(code: string, options: FormatCodeInterface = {}): string;
52
- ```
53
- Parameters
54
-
55
- * `code` (string): The source code or stack to be formatted.
56
- * `options` (FormatCodeInterface, optional): Configuration options for formatting the code.
57
- * `padding` (number, optional): Number of characters for line number padding. Defaults to 10.
58
- * `startLine` (number, optional): The starting line number for formatting. Defaults to 1.
59
- * `action` (object, optional): Custom actions to apply to specific lines.
60
- * `triggerLine` (number): The line number where the action should be triggered.
61
- * `callback` (function): A callback function to format the line string when triggerLine is matched. The callback receives the formatted line string, the padding value, and the current line number as arguments.
62
-
63
- ```typescript
64
- import { formatCode } from '@remotex-labs/xmap';
65
-
66
- // Example TypeScript code
67
- const code = `
68
- function helloWorld() {
69
- console.log('Hello, world!');
70
- }
71
- `;
72
-
73
- // Formatting the code
74
- const formattedCode = formatCode(code, {
75
- padding: 8,
76
- startLine: 5,
77
- action: {
78
- triggerLine: 7,
79
- callback: (lineString, padding, lineNumber) => {
80
- return `Custom formatting for line ${lineNumber}: ${lineString}`;
81
- }
82
- }
83
- });
84
- console.log(formattedCode);
85
- `;
86
-
87
- // Formatting the code
88
- const formattedCode = formatCode(code);
89
- console.log(formattedCode);
90
- ```
91
-
92
- ### Formatting Code with Error Location
93
- The formatErrorCode function formats a code snippet around an error location with special highlighting.\
94
- It highlights the relevant code snippet around the error location, including special formatting for the error line and column.
95
-
96
- Function Signature
97
- ```typescript
98
- export function formatErrorCode(sourcePosition: PositionSourceInterface, ansiOption?: AnsiOptionInterface): string;
99
- ```
100
-
101
- Example
102
- ```typescript
103
- import { formatErrorCode } from '@remotex-labs/xmap';
104
-
105
- // Example source position
106
- const sourcePosition = {
107
- code: `
108
- function helloWorld() {
109
- console.log('Hello, world!');
110
- }
111
- `,
112
- line: 2,
113
- column: 15,
114
- startLine: 1
115
- };
116
-
117
- // Optional ANSI color configuration
118
- const ansiOption = {
119
- color: '\x1b[38;5;160m', // Red color
120
- reset: '\x1b[0m' // Reset color
121
- };
122
-
123
- // Formatting the error code
124
- const formattedErrorCode = formatErrorCode(sourcePosition, ansiOption);
125
- console.log(formattedErrorCode);
126
- ```
127
-
128
- ### Highlighting Syntax
129
- To apply syntax highlighting to TypeScript or JavaScript code, use the highlighter component:
130
- ```typescript
131
- import { highlightCode } from '@remotex-labs/xmap';
132
-
133
- // Example TypeScript code
134
- const code = `
135
- function helloWorld() {
136
- console.log('Hello, world!');
137
- }
138
- `;
139
-
140
- // Highlighting the code
141
- const highlightedCode = highlightCode(code);
142
- console.log(highlightedCode);
143
- ```
1
+ # xMap Description
2
+ `xMap` is a library designed to help with sourcemap parsing and TypeScript code formatting for the CLI.\
3
+ It includes components for parsing error stack traces, formatting code, and providing syntax highlighting, as well as a service for handling source maps.
4
+
5
+ # Installation
6
+ To install the package, use npm or yarn:
7
+ ```bash
8
+ npm install @remotex-labs/xmap
9
+ ```
10
+ or
11
+ ```bash
12
+ yarn add @remotex-labs/xmap
13
+ ```
14
+ # Usage SourceService
15
+ A TypeScript service for validating and processing source maps.
16
+ The `SourceService` class provides functionality for parsing and manipulating source maps, including retrieving position mappings,
17
+ concatenating source maps, and getting code snippets based on mappings.
18
+
19
+ ### Importing the SourceService
20
+ You can import the SourceService class in your TypeScript project as follows:
21
+ ```typescript
22
+ import { SourceService } from '@remotex-labs/xmap'
23
+ ```
24
+
25
+ ## Creating an Instance of SourceService
26
+ You can create an instance of `SourceService` using either a `SourceMapInterface` object,
27
+ a JSON string representing the source map, or an existing `SourceService` instance.
28
+ Example:
29
+ ```typescript
30
+ const sourceMapJSON = `
31
+ {
32
+ "version": 3,
33
+ "sources": ["../src/core/core.component.ts", "../src/index.ts"],
34
+ "sourceRoot": "https://github.com/remotex-lab/xmap/tree/test/",
35
+ "sourcesContent": ["export class CoreModule {\\r\\n private name: string;\\r\\n\\r\\n constructor(name: string) {\\r\\n this.name = name;\\r\\n }\\r\\n\\r\\n public greet(): string {\\r\\n return \`Hello from \${ this.name }!\`;\\r\\n }\\r\\n}", "import { CoreModule } from '@core/core.component';\\r\\n\\r\\nconst coreInstance = new CoreModule('Core Module');\\r\\n\\r\\nconsole.log(coreInstance.greet());"],
36
+ "mappings": "aAAO,IAAMA,EAAN,KAAiB,CACZ,KAER,YAAYC,EAAc,CACtB,KAAK,KAAOA,CAChB,CAEO,OAAgB,CACnB,MAAO,cAAc,KAAK,IAAI,GAClC,CACJ,ECRA,IAAMC,EAAe,IAAIC,EAAW,aAAa,EAEjD,QAAQ,IAAID,EAAa,MAAM,CAAC",
37
+ "names": ["CoreModule", "name", "coreInstance", "CoreModule"]
38
+ }
39
+ `;
40
+ const sourceService = new SourceService(sourceMapJSON, 'bundle.js');
41
+ console.log(sourceService);
42
+ ```
43
+
44
+ ## Retrieving Position Information
45
+ You can retrieve position information based on the original source line and column using the `getPositionByOriginal` method.
46
+ Example:
47
+ ```typescript
48
+ const position = sourceService.getPositionByOriginal(3, 7, 'index.ts');
49
+ console.log(position);
50
+ ```
51
+ ## Getting Code Snippets
52
+ To retrieve the position and a code snippet from the original source based on the given generated code position,
53
+ you can use the `getPositionWithCode` method.
54
+ Example:
55
+ ```typescript
56
+ const positionWithCode = sourceService.getPositionWithCode(1, 104, Bias.UPPER_BOUND, { linesBefore: 2, linesAfter: 2 });
57
+ console.log(positionWithCode);
58
+ ```
59
+
60
+ ## Converting to JSON String
61
+ You can convert the current source map object to a JSON string using the `toString` method.
62
+ Example:
63
+ ```typescript
64
+ console.log(sourceService.toString());
65
+ ```
66
+
67
+ ## Concatenating Source Maps
68
+ To concatenate one or more source maps to the current source map, you can use the `concat` method.
69
+ ```typescript
70
+ const anotherSourceMap = {
71
+ version: 3,
72
+ file: "another-bundle.js",
73
+ sources: ["bar.ts"],
74
+ names: [],
75
+ mappings: "AAAA"
76
+ };
77
+
78
+ sourceService.concat(anotherSourceMap);
79
+ console.log(sourceService.sources); // Updated source paths
80
+ ```
81
+
82
+ ## Parsing Error Stack Traces
83
+ The parseErrorStack function parses an error stack trace and returns an array of stack entries.
84
+ Each entry contains information about the function call, file, line number, column number, and if applicable, details about the eval context.
85
+ Example:
86
+ ```typescript
87
+ import { parseErrorStack } from '@remotex-labs/xmap';
88
+
89
+ // Example stack trace string
90
+ const stackTrace = `
91
+ Error: Example error
92
+ at Object.<anonymous> (/path/to/file.js:10:15)
93
+ at Module._compile (node:internal/modules/cjs/loader:1217:14)
94
+ at node:internal/modules/cjs/loader:1308:14
95
+ at node:internal/modules/cjs/loader:1425:5
96
+ at node:internal/modules/cjs/loader:1425:5
97
+ at node:internal/modules/cjs/loader:1483:3
98
+ at node:internal/modules/cjs/loader:1700:8
99
+ at node:internal/modules/cjs/loader:1760:3
100
+ at /path/to/file.js:10:15
101
+ at Object.<anonymous> (/path/to/file.js:10:15)
102
+ at eval (eval at <anonymous> (/path/to/file.js:10:15), <anonymous>:1:1)
103
+ `;
104
+
105
+ // Parsing the stack trace
106
+ const parsedStack = parseErrorStack(stackTrace);
107
+ console.log(parsedStack);
108
+ ```
109
+
110
+ ## highlightCode
111
+ Highlights the provided TypeScript code based on a specified highlighting scheme.
112
+ This function creates a source file from the provided code string, walks through its nodes,
113
+ and applies syntax highlighting according to the given schema.
114
+
115
+ Example:
116
+ ```typescript
117
+ import { highlightCode } from '@remotex-labs/xmap';
118
+
119
+ // TypeScript code to be highlighted
120
+ const codeToHighlight = `
121
+ function greet(name: string): string {
122
+ return 'Hello, ' + name;
123
+ }
124
+ `;
125
+
126
+ // Optional custom highlight scheme
127
+ const customScheme = {
128
+ keywordColor: '\x1b[36m', // Blue
129
+ stringColor: '\x1b[32m', // Green
130
+ numberColor: '\x1b[31m' // Red
131
+ };
132
+
133
+ // Highlight the code
134
+ const highlightedCode = highlightCode(codeToHighlight);
135
+ const highlightedCode2 = highlightCode(codeToHighlight, customScheme);
136
+ const highlightedCode3 = highlightCode(codeToHighlight);
137
+
138
+ // Output the highlighted code
139
+ console.log(highlightedCode, highlightedCode2, highlightedCode3);
140
+ ```
141
+ > If you provide a customScheme, it will override the default highlighting scheme. This means you won't need to pass it each time you call highlightCode.
142
+
143
+ ![image](docs/images/code.png)
144
+ ## formatCode
145
+ The `formatCode` function formats a given code snippet, adding line numbers with customizable padding and enabling specific actions for particular lines.
146
+ This utility is useful for displaying code snippets in a user-friendly manner, particularly in documentation or debugging scenarios.
147
+
148
+ Example:
149
+ ```typescript
150
+ import { formatCode, highlightCode } from '@remotex-labs/xmap';
151
+
152
+ const code = `
153
+ function greet(name: string) {
154
+ console.log('Hello, ' + name);
155
+ }
156
+
157
+ greet('World');
158
+ `;
159
+
160
+ const formattedCode = formatCode(highlightCode(code), {
161
+ padding: 8,
162
+ startLine: 5,
163
+ action: {
164
+ triggerLine: 6,
165
+ callback: (lineString, padding, lineNumber) => {
166
+ return `*** Custom formatting for line ${lineNumber} ***\n${lineString}`;
167
+ }
168
+ }
169
+ });
170
+
171
+ console.log(formattedCode);
172
+ ```
173
+ ![image](docs/images/formatCode.png)
174
+
175
+ ## formatErrorCode
176
+ The `formatErrorCode` function formats a code snippet around a specified error location,
177
+ applying special highlighting to indicate where the error occurred. This function is particularly useful for debugging and error reporting,
178
+ as it helps to visually identify issues in the source code.
179
+
180
+ ```typescript
181
+ import { highlightCode, SourceService, formatErrorCode } from '@remotex-labs/xmap';
182
+
183
+ const sourceMapJSON = `
184
+ {
185
+ "version": 3,
186
+ "sources": ["../src/core/core.component.ts", "../src/index.ts"],
187
+ "sourceRoot": "https://github.com/remotex-lab/xmap/tree/test/",
188
+ "sourcesContent": ["export class CoreModule {\\r\\n private name: string;\\r\\n\\r\\n constructor(name: string) {\\r\\n this.name = name;\\r\\n }\\r\\n\\r\\n public greet(): string {\\r\\n return \`Hello from \${ this.name }!\`;\\r\\n }\\r\\n}", "import { CoreModule } from '@core/core.component';\\r\\n\\r\\nconst coreInstance = new CoreModule('Core Module');\\r\\n\\r\\nconsole.log(coreInstance.greet());"],
189
+ "mappings": "aAAO,IAAMA,EAAN,KAAiB,CACZ,KAER,YAAYC,EAAc,CACtB,KAAK,KAAOA,CAChB,CAEO,OAAgB,CACnB,MAAO,cAAc,KAAK,IAAI,GAClC,CACJ,ECRA,IAAMC,EAAe,IAAIC,EAAW,aAAa,EAEjD,QAAQ,IAAID,EAAa,MAAM,CAAC",
190
+ "names": ["CoreModule", "name", "coreInstance", "CoreModule"]
191
+ }
192
+ `;
193
+ const sourceService = new SourceService(sourceMapJSON, 'bundle.js');
194
+ const error = sourceService.getPositionWithCode(1, 91);
195
+
196
+ const ansiOption = {
197
+ color: '\x1b[38;5;160m', // Color for error marker
198
+ reset: '\x1b[0m' // Reset color
199
+ };
200
+
201
+ if (error) {
202
+ error.code = highlightCode(error.code);
203
+ console.log(formatErrorCode(error, ansiOption));
204
+ }
205
+ ```
206
+ ![image](docs/images/formatErrorCode.png)
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Import will remove at compile time
3
3
  */
4
- import type { PositionSourceInterface } from "../services/interfaces/source.interface.ts";
5
- import type { AnsiOptionInterface, FormatCodeInterface } from "./interfaces/formatter.interface.ts";
4
+ import type { PositionWithCodeInterface } from "../services/interfaces/source.interface";
5
+ import type { AnsiOptionInterface, FormatCodeInterface } from "./interfaces/formatter.interface";
6
6
  /**
7
7
  * Formats a code snippet with optional line padding and custom actions.
8
8
  *
@@ -63,4 +63,4 @@ export declare function formatCode(code: string, options?: FormatCodeInterface):
63
63
  * console.log(formattedErrorCode);
64
64
  * ```
65
65
  */
66
- export declare function formatErrorCode(sourcePosition: PositionSourceInterface, ansiOption?: AnsiOptionInterface): string;
66
+ export declare function formatErrorCode(sourcePosition: PositionWithCodeInterface, ansiOption?: AnsiOptionInterface): string;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Import will remove at compile time
3
3
  */
4
- import type { HighlightSchemeInterface } from "./interfaces/highlighter.interface.ts";
4
+ import type { HighlightSchemeInterface } from "./interfaces/highlighter.interface";
5
5
  /**
6
6
  * Imports
7
7
  */
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Import will remove at compile time
3
3
  */
4
- import type { StackEntryInterface } from "./interfaces/parse.interface.ts";
4
+ import type { StackEntryInterface } from "./interfaces/parse.interface";
5
5
  /**
6
6
  * Parses an error stack trace and returns an object with a message and an array of stack entries.
7
7
  *
@@ -0,0 +1,9 @@
1
+ export type * from "./components/interfaces/parse.interface";
2
+ export type * from "./components/interfaces/formatter.interface";
3
+ export type * from "./components/interfaces/highlighter.interface";
4
+ export type * from "./services/interfaces/source.interface";
5
+ export * from "./components/parser.component";
6
+ export * from "./components/base64.component";
7
+ export * from "./components/formatter.component";
8
+ export * from "./components/highlighter.component";
9
+ export * from "./services/source.service";
@@ -0,0 +1,7 @@
1
+ function $(u){let e=u.split(`
2
+ `).slice(1),t=/^\s*at\s+(.*?)\s+\((.*?):(\d+):(\d+)\)$|^\s*at\s+(.*?):(\d+):(\d+)$/,n=/eval\s+at\s+([^\s(]+).+\((.+):(\d+):(\d+)\),\s(.+)/,i=[];return e.forEach(r=>{let s=r.match(t);if(!s)return;let a=s.slice(1);s[2]||(a=s.slice(4));let[c,l,d,g]=a,h=parseInt(d,10),m=parseInt(g,10);if(r.includes("eval")){let y=l.match(n)?.slice(1);if(y){let[N,w,E,A,M]=y;i.push({at:c,file:M,line:h,column:m,executor:{at:N,file:w,line:parseInt(E,10),column:parseInt(A,10)}});return}}i.push({at:c||"<anonymous>",file:l,line:h,column:m,executor:null})}),i}var x={},I="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");I.forEach((u,e)=>{x[u]=e});function T(u){let e=u<0,t="",n=e?(-u<<1)+1:u<<1;do{let i=n&31;n>>>=5,t+=I[i|(n>0?32:0)]}while(n>0);return t}function C(u){return u.map(T).join("")}function b(u){let e=[],t=0,n=0;for(let i=0;i<u.length;i++){let r=x[u[i]];if(r===void 0)throw new Error(`Invalid Base64 character: ${u[i]}`);let s=r&32;if(n+=(r&31)<<t,s)t+=5;else{let a=(n&1)===1,c=n>>1;e.push(a?-c:c),n=t=0}}return e}function K(u,e={}){let t=u.split(`
3
+ `),n=e.padding??10,i=e.startLine??0;return t.map((r,s)=>{let a=s+i+1,l=`${`${a} | `.padStart(n)}${r}`;return e.action&&a===e.action.triggerLine?e.action.callback(l,n,a):l}).join(`
4
+ `)}function F(u,e){let{code:t,line:n,column:i,startLine:r}=u;if(n<r||i<1)throw new Error("Invalid line or column number.");return K(t,{startLine:r,action:{triggerLine:n,callback:(s,a,c)=>{let l="^",d=a-1,g=">";e&&(l=`${e.color}${l}${e.reset}`,d+=e.color.length+e.reset.length,g=`${e.color}>${e.reset}`);let h=" | ".padStart(a)+" ".repeat(i-1)+`${l}`;return s=`${g} ${c} |`.padStart(d)+s.split("|")[1],s+`
5
+ ${h}`}}})}import*as o from"typescript";import{SyntaxKind as p}from"typescript";var O=(m=>(m.reset="\x1B[0m",m.gray="\x1B[38;5;243m",m.darkGray="\x1B[38;5;238m",m.lightCoral="\x1B[38;5;203m",m.lightOrange="\x1B[38;5;215m",m.oliveGreen="\x1B[38;5;149m",m.burntOrange="\x1B[38;5;208m",m.lightGoldenrodYellow="\x1B[38;5;221m",m.lightYellow="\x1B[38;5;230m",m.canaryYellow="\x1B[38;5;227m",m.deepOrange="\x1B[38;5;166m",m.lightGray="\x1B[38;5;252m",m.brightPink="\x1B[38;5;197m",m))(O||{}),L={enumColor:"\x1B[38;5;208m",typeColor:"\x1B[38;5;221m",classColor:"\x1B[38;5;215m",stringColor:"\x1B[38;5;149m",keywordColor:"\x1B[38;5;203m",commentColor:"\x1B[38;5;238m",functionColor:"\x1B[38;5;215m",variableColor:"\x1B[38;5;208m",interfaceColor:"\x1B[38;5;221m",parameterColor:"\x1B[38;5;166m",getAccessorColor:"\x1B[38;5;230m",numericLiteralColor:"\x1B[38;5;252m",methodSignatureColor:"\x1B[38;5;208m",regularExpressionColor:"\x1B[38;5;149m",propertyAssignmentColor:"\x1B[38;5;227m",propertyAccessExpressionColor:"\x1B[38;5;230m",expressionWithTypeArgumentsColor:"\x1B[38;5;215m"},S=class{constructor(e,t,n){this.sourceFile=e;this.code=t;this.schema=n}segments=new Map;parseNode(e){this.processComments(e),this.processKeywords(e),this.processNode(e)}highlight(){let e=0,t,n=[];return Array.from(this.segments.values()).sort((r,s)=>r.start-s.start||r.end-s.end).forEach(r=>{if(t&&r.start<t.end){let s=n.pop();if(!s)return;let a=this.getSegmentSource(r.start,r.end),c=`${r.color}${a}${t.color}`;n.push(s.replace(a,c));return}n.push(this.getSegmentSource(e,r.start)),n.push(`${r.color}${this.getSegmentSource(r.start,r.end)}${r.reset}`),e=r.end,t=r}),n.join("")+this.getSegmentSource(e)}getSegmentSource(e,t){return this.code.slice(e,t)}addSegment(e,t,n,i="\x1B[0m"){let r=`${e}-${t}`;this.segments.set(r,{start:e,end:t,color:n,reset:i})}processComments(e){[...o.getTrailingCommentRanges(this.sourceFile.getFullText(),e.getFullStart())||[],...o.getLeadingCommentRanges(this.sourceFile.getFullText(),e.getFullStart())||[]].forEach(n=>this.addSegment(n.pos,n.end,this.schema.commentColor))}processKeywords(e){if([p.NullKeyword,p.VoidKeyword,p.StringKeyword,p.NumberKeyword,p.BooleanKeyword,p.UndefinedKeyword].includes(e.kind))return this.addSegment(e.getStart(),e.getEnd(),this.schema.typeColor);e&&e.kind>=o.SyntaxKind.FirstKeyword&&e.kind<=o.SyntaxKind.LastKeyword&&this.addSegment(e.getStart(),e.getEnd(),this.schema.keywordColor)}processIdentifier(e){let t=e.getEnd(),n=e.getStart();switch(e.parent.kind){case o.SyntaxKind.EnumMember:return this.addSegment(n,t,this.schema.enumColor);case o.SyntaxKind.CallExpression:case o.SyntaxKind.EnumDeclaration:case o.SyntaxKind.PropertySignature:case o.SyntaxKind.ModuleDeclaration:return this.addSegment(n,t,this.schema.variableColor);case o.SyntaxKind.InterfaceDeclaration:return this.addSegment(n,t,this.schema.interfaceColor);case o.SyntaxKind.GetAccessor:return this.addSegment(n,t,this.schema.getAccessorColor);case o.SyntaxKind.PropertyAssignment:return this.addSegment(n,t,this.schema.propertyAssignmentColor);case o.SyntaxKind.MethodSignature:return this.addSegment(n,t,this.schema.methodSignatureColor);case o.SyntaxKind.MethodDeclaration:case o.SyntaxKind.FunctionDeclaration:return this.addSegment(n,t,this.schema.functionColor);case o.SyntaxKind.ClassDeclaration:return this.addSegment(n,t,this.schema.classColor);case o.SyntaxKind.Parameter:return this.addSegment(n,t,this.schema.parameterColor);case o.SyntaxKind.VariableDeclaration:return this.addSegment(n,t,this.schema.variableColor);case o.SyntaxKind.PropertyDeclaration:return this.addSegment(n,t,this.schema.variableColor);case o.SyntaxKind.PropertyAccessExpression:return e.parent.getChildAt(0).getText()===e.getText()?this.addSegment(n,t,this.schema.variableColor):this.addSegment(n,t,this.schema.propertyAccessExpressionColor);case o.SyntaxKind.ExpressionWithTypeArguments:return this.addSegment(n,t,this.schema.expressionWithTypeArgumentsColor);case o.SyntaxKind.BreakStatement:case o.SyntaxKind.ShorthandPropertyAssignment:case o.SyntaxKind.BindingElement:return this.addSegment(n,t,this.schema.variableColor);case o.SyntaxKind.BinaryExpression:case o.SyntaxKind.SwitchStatement:case o.SyntaxKind.TemplateSpan:return this.addSegment(n,t,this.schema.variableColor);case o.SyntaxKind.TypeReference:case o.SyntaxKind.TypeAliasDeclaration:return this.addSegment(n,t,this.schema.typeColor);case o.SyntaxKind.NewExpression:return this.addSegment(n,t,this.schema.variableColor)}}processTemplateExpression(e){let t=e.head.getStart(),n=e.head.getEnd();this.addSegment(t,n,this.schema.stringColor),e.templateSpans.forEach(i=>{let r=i.literal.getStart(),s=i.literal.getEnd();this.addSegment(r,s,this.schema.stringColor)})}processNode(e){let t=e.getStart(),n=e.getEnd();switch(e.kind){case o.SyntaxKind.TypeParameter:return this.addSegment(t,t+e.name.text.length,this.schema.typeColor);case o.SyntaxKind.TypeReference:return this.addSegment(t,n,this.schema.typeColor);case o.SyntaxKind.StringLiteral:case o.SyntaxKind.NoSubstitutionTemplateLiteral:return this.addSegment(t,n,this.schema.stringColor);case o.SyntaxKind.RegularExpressionLiteral:return this.addSegment(t,n,this.schema.regularExpressionColor);case o.SyntaxKind.TemplateExpression:return this.processTemplateExpression(e);case o.SyntaxKind.Identifier:return this.processIdentifier(e);case o.SyntaxKind.BigIntLiteral:case o.SyntaxKind.NumericLiteral:return this.addSegment(t,n,this.schema.numericLiteralColor)}}};function D(u,e={}){let t=o.createSourceFile("temp.ts",u,o.ScriptTarget.Latest,!0,o.ScriptKind.TS),n=new S(t,u,Object.assign(L,e));function i(r){n.parseNode(r);for(let s=0;s<r.getChildCount();s++)i(r.getChildAt(s))}return o.forEachChild(t,i),n.highlight()}var f=class u{mapping=[];constructor(e,t=0,n=0){e=e instanceof u?e.mapping:e,Array.isArray(e)?this.decodeMappingArray(e,t,n):this.decodeMappingString(e,t,n)}encode(){return this.encodeMappings(this.mapping)}decode(e,t=0,n=0){e=e instanceof u?e.mapping:e,Array.isArray(e)?this.decodeMappingArray(e,t,n):this.decodeMappingString(e,t,n)}getSegment(e,t,n=0){let i=this.mapping[e-1];if(!i||i.length===0)return null;let r=0,s=i.length-1,a=null;for(;r<=s;){let c=Math.floor((r+s)/2),l=i[c];if(l.generatedColumn<t)r=c+1,a=n===1?l:a;else if(l.generatedColumn>t)s=c-1,a=n===2?l:a;else return l}return a}getOriginalSegment(e,t,n,i=0){let r=null;for(let s of this.mapping){if(!s)continue;let a=0,c=s.length-1;for(;a<=c;){let l=Math.floor((a+c)/2),d=s[l];if(d.sourceIndex<n||d.line<e)a=l+1;else if(d.sourceIndex>n||d.line>e)c=l-1;else if(d.column<t)a=l+1,r=i===1?d:r;else if(d.column>t)c=l-1,r=i===2?d:r;else return d}}return r}initPositionOffsets(e=0,t=0){return{line:0,column:0,nameIndex:e,sourceIndex:t,generatedLine:0,generatedColumn:0}}validateMappingString(e){return/^(;*([A-Za-z0-9+/]{1,7}(([,]|[;]+)[A-Za-z0-9+/]{1,7})*));*$/.test(e)}validateSegment(e){if(!Number.isFinite(e.line))throw new Error(`Invalid segment: line must be a finite number, received ${e.line}`);if(!Number.isFinite(e.column))throw new Error(`Invalid segment: column must be a finite number, received ${e.column}`);if(e.nameIndex!==null&&!Number.isFinite(e.nameIndex))throw new Error(`Invalid segment: nameIndex must be a number or null, received ${e.nameIndex}`);if(!Number.isFinite(e.sourceIndex))throw new Error(`Invalid segment: sourceIndex must be a finite number, received ${e.sourceIndex}`);if(!Number.isFinite(e.generatedLine))throw new Error(`Invalid segment: generatedLine must be a finite number, received ${e.generatedLine}`);if(!Number.isFinite(e.generatedColumn))throw new Error(`Invalid segment: generatedColumn must be a finite number, received ${e.generatedColumn}`)}encodeSegment(e,t){let{line:n,column:i,generatedColumn:r,nameIndex:s,sourceIndex:a}=t,c=n-1,l=i-1,d=r-1,g=[d-e.generatedColumn,a!==e.sourceIndex?a-e.sourceIndex:0,c-e.line,l-e.column];return s!=null&&(g[4]=s-e.nameIndex,e.nameIndex=s),e.line=c,e.column=l,e.generatedColumn=d,e.sourceIndex=a,C(g)}encodeMappings(e){let t=this.initPositionOffsets();return e.map(n=>n?(t.generatedColumn=0,n.map(r=>this.encodeSegment(t,r)).join(",")):"").join(";")}decodedSegment(e,t){let[n,i,r,s,a]=t;return e.line+=r,e.column+=s,e.nameIndex+=a??0,e.sourceIndex+=i,e.generatedColumn+=n,{line:e.line+1,column:e.column+1,nameIndex:a!==void 0?e.nameIndex:null,sourceIndex:e.sourceIndex,generatedLine:e.generatedLine+1,generatedColumn:e.generatedColumn+1}}decodeMappingString(e,t,n){if(!this.validateMappingString(e))throw new Error("Invalid Mappings string format: the provided string does not conform to expected VLQ format.");let i=e.split(";"),r=this.mapping.length,s=this.initPositionOffsets(t,n);try{i.forEach((a,c)=>{if(!a){this.mapping.push(null);return}s.generatedColumn=0,s.generatedLine=r+c;let l=a.split(",").map(d=>this.decodedSegment(s,b(d)));this.mapping.push(l)})}catch(a){throw new Error(`Error decoding mappings at frame index ${i.length}: ${a.message}`)}}decodeMappingArray(e,t,n){let i=this.mapping.length;if(!Array.isArray(e))throw new Error("Invalid encoded map: expected an array of frames.");try{e.forEach((r,s)=>{if(!r){this.mapping.push(r);return}if(!Array.isArray(r))throw new Error(`Invalid Mappings array format at frame index ${s}: expected an array, received ${typeof r}.`);let a=r.map(c=>(this.validateSegment(c),{...c,nameIndex:typeof c.nameIndex=="number"?c.nameIndex+t:null,sourceIndex:c.sourceIndex+n,generatedLine:c.generatedLine+i}));this.mapping.push(a)})}catch(r){let s=r instanceof Error?r.message:"Unknown error";throw new Error(`Error decoding mappings: ${s}`)}}};var v=class u{file;mappings;sourceRoot;names;sources;sourcesContent;constructor(e,t=null){typeof e=="string"&&(e=JSON.parse(e)),e=e,this.validateSourceMap(e),this.file=e.file??t,this.names=[...e.names??[]],this.sources=[...e.sources??[]],this.sourceRoot=e.sourceRoot??null,this.sourcesContent=e.sourcesContent?[...e.sourcesContent]:[],this.mappings=new f(e.mappings)}getMapObject(){let e={version:3,names:this.names,sources:this.sources,mappings:this.mappings.encode(),sourcesContent:this.sourcesContent};return this.file&&(e.file=this.file),this.sourceRoot&&(e.sourceRoot=this.sourceRoot),e}concat(...e){if(e.length<1)throw new Error("At least one map must be provided for concatenation.");for(let t of e)this.mappings.decode(t.mappings,this.names.length,this.sources.length),this.names.push(...t.names),this.sources.push(...t.sources),this.sourcesContent.push(...t.sourcesContent??[])}concatNewMap(...e){if(e.length<1)throw new Error("At least one map must be provided for concatenation.");let t=new u(this);for(let n of e)t.mappings.decode(n.mappings,t.names.length,t.sources.length),t.names.push(...n.names),t.sources.push(...n.sources),t.sourcesContent.push(...n.sourcesContent??[]);return t}getPositionByOriginal(e,t,n,i=0){let r=n;if(typeof n=="string"&&(r=this.sources.findIndex(a=>a.includes(n))),r<0)return null;let s=this.mappings.getOriginalSegment(e,t,r,i);return s?{name:this.names[s.nameIndex??-1]??null,line:s.line,column:s.column,source:this.sources[s.sourceIndex],sourceRoot:this.sourceRoot,sourceIndex:s.sourceIndex,generatedLine:s.generatedLine,generatedColumn:s.generatedColumn}:null}getPosition(e,t,n=0){let i=this.mappings.getSegment(e,t,n);return i?{name:this.names[i.nameIndex??-1]??null,line:i.line,column:i.column,source:this.sources[i.sourceIndex],sourceRoot:this.sourceRoot,sourceIndex:i.sourceIndex,generatedLine:i.generatedLine,generatedColumn:i.generatedColumn}:null}getPositionWithContent(e,t,n=0){let i=this.getPosition(e,t,n);return i?{...i,sourcesContent:this.sourcesContent[i.sourceIndex]}:null}getPositionWithCode(e,t,n=0,i){let r=this.getPosition(e,t,n);if(!r||!this.sourcesContent[r.sourceIndex])return null;let s=Object.assign({linesAfter:4,linesBefore:3},i),a=this.sourcesContent[r.sourceIndex].split(`
6
+ `),c=Math.min((r.line??1)+s.linesAfter,a.length),l=Math.max((r.line??1)-s.linesBefore,0),d=a.slice(l,Math.min(c+1,a.length)).join(`
7
+ `);return{...r,code:d,endLine:c,startLine:l}}toString(){return JSON.stringify(this.getMapObject())}validateSourceMap(e){if(!["sources","mappings","names"].every(n=>n in e))throw new Error("Missing required keys in SourceMap.")}};export{S as CodeHighlighter,O as Colors,v as SourceService,b as decodeVLQ,C as encodeArrayVLQ,T as encodeVLQ,K as formatCode,F as formatErrorCode,D as highlightCode,$ as parseErrorStack};