@astrojs/ts-plugin 0.3.0 → 0.4.1

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 (52) hide show
  1. package/.turbo/turbo-build.log +5 -2
  2. package/CHANGELOG.md +16 -0
  3. package/LICENSE +36 -0
  4. package/dist/astro-snapshots.js +48 -47
  5. package/dist/astro-sys.js +22 -35
  6. package/dist/astro2tsx.js +22 -26
  7. package/dist/index.js +38 -39
  8. package/dist/language-service/completions.js +42 -42
  9. package/dist/language-service/definition.js +22 -40
  10. package/dist/language-service/diagnostics.js +15 -18
  11. package/dist/language-service/file-references.js +52 -0
  12. package/dist/language-service/find-references.js +20 -38
  13. package/dist/language-service/implementation.js +18 -37
  14. package/dist/language-service/index.js +26 -42
  15. package/dist/language-service/line-column-offset.js +44 -0
  16. package/dist/language-service/rename.js +24 -37
  17. package/dist/logger.js +18 -5
  18. package/dist/module-loader.js +28 -22
  19. package/dist/project-astro-files.js +125 -0
  20. package/dist/utils.js +34 -19
  21. package/dist/workers/TSXService.js +39 -0
  22. package/dist/workers/TSXWorker.js +9 -0
  23. package/package.json +21 -11
  24. package/src/astro-snapshots.ts +17 -26
  25. package/src/astro-sys.ts +1 -1
  26. package/src/astro2tsx.ts +5 -46
  27. package/src/index.ts +34 -34
  28. package/src/language-service/completions.ts +15 -4
  29. package/src/language-service/definition.ts +2 -7
  30. package/src/language-service/diagnostics.ts +1 -2
  31. package/src/language-service/file-references.ts +31 -0
  32. package/src/language-service/find-references.ts +2 -2
  33. package/src/language-service/implementation.ts +2 -7
  34. package/src/language-service/index.ts +10 -25
  35. package/src/language-service/line-column-offset.ts +21 -0
  36. package/src/language-service/rename.ts +2 -2
  37. package/src/module-loader.ts +12 -4
  38. package/src/project-astro-files.ts +130 -0
  39. package/src/utils.ts +29 -20
  40. package/src/workers/TSXService.ts +11 -0
  41. package/src/workers/TSXWorker.ts +8 -0
  42. package/test/fixtures/MyAstroComponent.astro +5 -0
  43. package/test/fixtures/script.ts +9 -0
  44. package/test/fixtures/tsconfig.json +3 -0
  45. package/test/runTest.js +41 -0
  46. package/test/suite/extension.test.js +68 -0
  47. package/test/suite/index.js +38 -0
  48. package/test/tsconfig.json +14 -0
  49. package/test/utils.js +65 -0
  50. package/tsconfig.json +2 -1
  51. package/dist/source-mapper.js +0 -110
  52. package/src/source-mapper.ts +0 -107
package/src/utils.ts CHANGED
@@ -18,26 +18,6 @@ export function isNotNullOrUndefined<T>(val: T | undefined | null): val is T {
18
18
  return val !== undefined && val !== null;
19
19
  }
20
20
 
21
- /**
22
- * Checks if this a section that should be completely ignored
23
- * because it's purely generated.
24
- */
25
- export function isInGeneratedCode(text: string, start: number, end: number) {
26
- const lineStart = text.lastIndexOf('\n', start);
27
- const lineEnd = text.indexOf('\n', end);
28
- const lastStart = text.substring(lineStart, start).lastIndexOf('/*Ωignore_startΩ*/');
29
- const lastEnd = text.substring(lineStart, start).lastIndexOf('/*Ωignore_endΩ*/');
30
- return lastStart > lastEnd && text.substring(end, lineEnd).includes('/*Ωignore_endΩ*/');
31
- }
32
-
33
- /**
34
- * Checks that this isn't a text span that should be completely ignored
35
- * because it's purely generated.
36
- */
37
- export function isNoTextSpanInGeneratedCode(text: string, span: ts.TextSpan) {
38
- return !isInGeneratedCode(text, span.start, span.start + span.length);
39
- }
40
-
41
21
  /**
42
22
  * Replace all occurrences of a string within an object with another string,
43
23
  */
@@ -64,3 +44,32 @@ export function replaceDeep<T extends Record<string, any>>(
64
44
  return _obj;
65
45
  }
66
46
  }
47
+
48
+ export function getConfigPathForProject(project: ts.server.Project) {
49
+ return (
50
+ (project as ts.server.ConfiguredProject).canonicalConfigFilePath ??
51
+ (project.getCompilerOptions() as any).configFilePath
52
+ );
53
+ }
54
+
55
+ export function readProjectAstroFilesFromFs(
56
+ ts: typeof import('typescript/lib/tsserverlibrary'),
57
+ project: ts.server.Project,
58
+ parsedCommandLine: ts.ParsedCommandLine
59
+ ) {
60
+ const fileSpec: TsFilesSpec = parsedCommandLine.raw;
61
+ const { include, exclude } = fileSpec;
62
+
63
+ if (include?.length === 0) {
64
+ return [];
65
+ }
66
+
67
+ return ts.sys
68
+ .readDirectory(project.getCurrentDirectory() || process.cwd(), ['.astro'], exclude, include)
69
+ .map(ts.server.toNormalizedPath);
70
+ }
71
+
72
+ export interface TsFilesSpec {
73
+ include?: readonly string[];
74
+ exclude?: readonly string[];
75
+ }
@@ -0,0 +1,11 @@
1
+ import type { TSXResult } from '@astrojs/compiler/shared/types';
2
+ import { createSyncFn } from 'synckit';
3
+
4
+ const convertToTSXSync = createSyncFn(require.resolve('./TSXWorker'));
5
+
6
+ /**
7
+ * Parse code by `@astrojs/compiler`
8
+ */
9
+ export function convertToTSX(source: string, options: { sourcefile: string }): TSXResult {
10
+ return convertToTSXSync(source, options);
11
+ }
@@ -0,0 +1,8 @@
1
+ import { runAsWorker } from 'synckit';
2
+
3
+ const dynamicImport = new Function('m', 'return import(m)');
4
+ runAsWorker(async (source: string, options: { sourcefile: string }) => {
5
+ const { convertToTSX } = await dynamicImport('@astrojs/compiler');
6
+ const result: any = convertToTSX(source, options);
7
+ return result;
8
+ });
@@ -0,0 +1,5 @@
1
+ ---
2
+ import { Hello, sayHello } from "./script"
3
+
4
+ class MyHello implements Hello {}
5
+ ---
@@ -0,0 +1,9 @@
1
+ export function sayHello() {
2
+ console.log("Hello")
3
+ }
4
+
5
+ MyAstroCompon
6
+
7
+ export class Hello {
8
+
9
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ // Purposely empty, this is done so TypeScript knows where the root of the project is and doesn't try to go too high into the monorepo
3
+ }
@@ -0,0 +1,41 @@
1
+ const path = require('path');
2
+ const { runTests } = require('@vscode/test-electron');
3
+ const { downloadDirToExecutablePath } = require('./utils');
4
+ const { existsSync, readdirSync } = require('fs');
5
+
6
+ async function main() {
7
+ try {
8
+ // The folder containing the Extension Manifest package.json
9
+ // Passed to `--extensionDevelopmentPath`
10
+ const extensionDevelopmentPath = path.resolve(__dirname, '../../vscode');
11
+
12
+ // The path to the extension test script
13
+ // Passed to --extensionTestsPath
14
+ const extensionTestsPath = path.resolve(__dirname, './suite/index.js');
15
+
16
+ // If there's already a downloaded version of VS Code, let's use it
17
+ const vscodeTestPath = path.resolve(__dirname, '../../vscode/.vscode-test');
18
+ let vsPath = undefined;
19
+ if (existsSync(vscodeTestPath)) {
20
+ const files = readdirSync(vscodeTestPath);
21
+ files.forEach((file) => {
22
+ if (file.startsWith('vscode-')) {
23
+ vsPath = downloadDirToExecutablePath(path.resolve(__dirname, '../../vscode/.vscode-test/', file));
24
+ return;
25
+ }
26
+ });
27
+ }
28
+
29
+ await runTests({
30
+ extensionDevelopmentPath,
31
+ extensionTestsPath,
32
+ vscodeExecutablePath: vsPath,
33
+ launchArgs: ['./fixtures/fixtures.code-workspace'],
34
+ });
35
+ } catch (err) {
36
+ console.error('Failed to run tests');
37
+ process.exit(1);
38
+ }
39
+ }
40
+
41
+ main();
@@ -0,0 +1,68 @@
1
+ const assert = require('assert');
2
+ const { expect } = require('chai');
3
+ const path = require('path');
4
+ const vscode = require('vscode');
5
+
6
+ suite('Extension Test Suite', () => {
7
+ vscode.window.showInformationMessage('Start all tests.');
8
+
9
+ // TypeScript takes a while to wake up and there's unfortunately no good way to wait for it
10
+ async function waitForTS(command, commandArgs, condition) {
11
+ for (let i = 0; i < 1000; i++) {
12
+ const commandResult = await vscode.commands.executeCommand(command, ...commandArgs);
13
+ if (condition(commandResult)) {
14
+ return commandResult;
15
+ }
16
+ await new Promise((resolve) => setTimeout(resolve, 100));
17
+ }
18
+ throw new Error(`TypeScript plugin never started or condition never resolved for command ${command}`);
19
+ }
20
+
21
+ test('extension is enabled', async () => {
22
+ const ext = vscode.extensions.getExtension('astro-build.astro-vscode');
23
+ const activate = await ext?.activate();
24
+
25
+ assert.notStrictEqual(activate, undefined);
26
+ });
27
+
28
+ test('can find references inside Astro files', async () => {
29
+ const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(path.join(__dirname, '../fixtures/script.ts')));
30
+
31
+ const references = await waitForTS(
32
+ 'vscode.executeReferenceProvider',
33
+ [doc.uri, new vscode.Position(0, 18)],
34
+ (result) => result.length > 1
35
+ );
36
+
37
+ const hasAstroRef = references.some((ref) => ref.uri.path.includes('MyAstroComponent.astro'));
38
+ expect(hasAstroRef).to.be.true;
39
+ }).timeout(22000);
40
+
41
+ test('can get completions for Astro components', async () => {
42
+ const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(path.join(__dirname, '../fixtures/script.ts')));
43
+
44
+ const completions = await waitForTS(
45
+ 'vscode.executeCompletionItemProvider',
46
+ [doc.uri, new vscode.Position(4, 12)],
47
+ (result) => result.items.length > 0
48
+ );
49
+
50
+ const hasAstroCompletion = completions.items.some((item) => {
51
+ return item.insertText === 'MyAstroComponent';
52
+ });
53
+ expect(hasAstroCompletion).to.be.true;
54
+ }).timeout(12000);
55
+
56
+ test('can get implementations inside Astro files', async () => {
57
+ const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(path.join(__dirname, '../fixtures/script.ts')));
58
+
59
+ const implementations = await waitForTS(
60
+ 'vscode.executeImplementationProvider',
61
+ [doc.uri, new vscode.Position(6, 15)],
62
+ (result) => result.length > 1
63
+ );
64
+
65
+ const hasAstroImplementation = implementations.some((impl) => impl.uri.path.includes('MyAstroComponent'));
66
+ expect(hasAstroImplementation).to.be.true;
67
+ }).timeout(12000);
68
+ });
@@ -0,0 +1,38 @@
1
+ const path = require('path');
2
+ const Mocha = require('mocha');
3
+ const glob = require('glob');
4
+
5
+ exports.run = function () {
6
+ // Create the mocha test
7
+ const mocha = new Mocha({
8
+ ui: 'tdd',
9
+ color: true,
10
+ });
11
+
12
+ const testsRoot = path.resolve(__dirname, '..');
13
+
14
+ return new Promise((c, e) => {
15
+ glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
16
+ if (err) {
17
+ return e(err);
18
+ }
19
+
20
+ // Add files to the test suite
21
+ files.forEach((f) => mocha.addFile(path.resolve(testsRoot, f)));
22
+
23
+ try {
24
+ // Run the mocha test
25
+ mocha.run((failures) => {
26
+ if (failures > 0) {
27
+ e(new Error(`${failures} tests failed.`));
28
+ } else {
29
+ c();
30
+ }
31
+ });
32
+ // eslint-disable-next-line @typescript-eslint/no-shadow
33
+ } catch (err) {
34
+ e(err);
35
+ }
36
+ });
37
+ });
38
+ };
@@ -0,0 +1,14 @@
1
+ {
2
+ "extends": "../tsconfig.json",
3
+ "compilerOptions": {
4
+ "module": "ES2020",
5
+ "target": "ES2020",
6
+ "moduleResolution": "node",
7
+ "allowJs": true,
8
+ "checkJs": false,
9
+ "rootDir": ".",
10
+ "emitDeclarationOnly": false,
11
+ "noEmit": true
12
+ },
13
+ "include": ["**/*.js"]
14
+ }
package/test/utils.js ADDED
@@ -0,0 +1,65 @@
1
+ /* MIT License
2
+
3
+ Copyright (c) Microsoft Corporation. All rights reserved.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE */
22
+
23
+ // @vscode/test-electron doesn't export this, so copying it here
24
+ // https://github.com/microsoft/vscode-test/blob/c6092b087a9c795c6d2097e864ab13e89d825226/lib/util.ts
25
+
26
+ const path = require('path');
27
+
28
+ /**
29
+ * @type {string}
30
+ */
31
+ let systemDefaultPlatform;
32
+ const windowsPlatforms = new Set(['win32-archive', 'win32-x64-archive', 'win32-arm64-archive']);
33
+ const darwinPlatforms = new Set(['darwin-arm64', 'darwin']);
34
+
35
+ switch (process.platform) {
36
+ case 'darwin':
37
+ systemDefaultPlatform = process.arch === 'arm64' ? 'darwin-arm64' : 'darwin';
38
+ break;
39
+ case 'win32':
40
+ systemDefaultPlatform =
41
+ process.arch === 'arm64'
42
+ ? 'win32-arm64-archive'
43
+ : process.arch === 'ia32'
44
+ ? 'win32-archive'
45
+ : 'win32-x64-archive';
46
+ break;
47
+ default:
48
+ systemDefaultPlatform =
49
+ process.arch === 'arm64' ? 'linux-arm64' : process.arch === 'arm' ? 'linux-armhf' : 'linux-x64';
50
+ }
51
+
52
+ /**
53
+ * @param {string} dir
54
+ */
55
+ function downloadDirToExecutablePath(dir) {
56
+ if (windowsPlatforms.has(systemDefaultPlatform)) {
57
+ return path.resolve(dir, 'Code.exe');
58
+ } else if (darwinPlatforms.has(systemDefaultPlatform)) {
59
+ return path.resolve(dir, 'Visual Studio Code.app/Contents/MacOS/Electron');
60
+ } else {
61
+ return path.resolve(dir, 'code');
62
+ }
63
+ }
64
+
65
+ module.exports = { downloadDirToExecutablePath };
package/tsconfig.json CHANGED
@@ -4,7 +4,8 @@
4
4
  "outDir": "dist",
5
5
  "rootDir": "src",
6
6
  "target": "ES2020",
7
- "module": "CommonJS"
7
+ "module": "CommonJS",
8
+ "importsNotUsedAsValues": "error"
8
9
  },
9
10
  "include": ["src"],
10
11
  "exclude": ["node_modules"]
@@ -1,110 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, {get: all[name], enumerable: true});
11
- };
12
- var __reExport = (target, module2, desc) => {
13
- if (module2 && typeof module2 === "object" || typeof module2 === "function") {
14
- for (let key of __getOwnPropNames(module2))
15
- if (!__hasOwnProp.call(target, key) && key !== "default")
16
- __defProp(target, key, {get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable});
17
- }
18
- return target;
19
- };
20
- var __toModule = (module2) => {
21
- return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? {get: () => module2.default, enumerable: true} : {value: module2, enumerable: true})), module2);
22
- };
23
- __markAsModule(exports);
24
- __export(exports, {
25
- SourceMapper: () => SourceMapper
26
- });
27
- var import_sourcemap_codec = __toModule(require("sourcemap-codec"));
28
- function binaryInsert(array, value, key) {
29
- if (key === 0)
30
- key = "0";
31
- const index = 1 + binarySearch(array, key ? value[key] : value, key);
32
- let i = array.length;
33
- while (index !== i--)
34
- array[1 + i] = array[i];
35
- array[index] = value;
36
- }
37
- function binarySearch(array, target, key) {
38
- if (!array || array.length === 0)
39
- return -1;
40
- if (key === 0)
41
- key = "0";
42
- let low = 0;
43
- let high = array.length - 1;
44
- while (low <= high) {
45
- const i = low + (high - low >> 1);
46
- const item = key === void 0 ? array[i] : array[i][key];
47
- if (item === target)
48
- return i;
49
- if (item < target)
50
- low = i + 1;
51
- else
52
- high = i - 1;
53
- }
54
- if ((low = ~low) < 0)
55
- low = ~low - 1;
56
- return low;
57
- }
58
- class SourceMapper {
59
- constructor(mappings) {
60
- if (typeof mappings === "string")
61
- this.mappings = (0, import_sourcemap_codec.decode)(mappings);
62
- else
63
- this.mappings = mappings;
64
- }
65
- getOriginalPosition(position) {
66
- const lineMap = this.mappings[position.line];
67
- if (!lineMap) {
68
- return {line: -1, character: -1};
69
- }
70
- const closestMatch = binarySearch(lineMap, position.character, 0);
71
- const match = lineMap[closestMatch];
72
- if (!match) {
73
- return {line: -1, character: -1};
74
- }
75
- const {2: line, 3: character} = match;
76
- return {line, character};
77
- }
78
- getGeneratedPosition(position) {
79
- if (!this.reverseMappings)
80
- this.computeReversed();
81
- const lineMap = this.reverseMappings[position.line];
82
- if (!lineMap) {
83
- return {line: -1, character: -1};
84
- }
85
- const closestMatch = binarySearch(lineMap, position.character, 0);
86
- const match = lineMap[closestMatch];
87
- if (!match) {
88
- return {line: -1, character: -1};
89
- }
90
- const {1: line, 2: character} = match;
91
- return {line, character};
92
- }
93
- computeReversed() {
94
- this.reverseMappings = {};
95
- for (let generated_line = 0; generated_line !== this.mappings.length; generated_line++) {
96
- for (const {0: generated_index, 2: original_line, 3: original_character_index} of this.mappings[generated_line]) {
97
- const reordered_char = [original_character_index, generated_line, generated_index];
98
- if (original_line in this.reverseMappings)
99
- binaryInsert(this.reverseMappings[original_line], reordered_char, 0);
100
- else
101
- this.reverseMappings[original_line] = [reordered_char];
102
- }
103
- }
104
- }
105
- }
106
- // Annotate the CommonJS export names for ESM import in node:
107
- 0 && (module.exports = {
108
- SourceMapper
109
- });
110
- //# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL3NvdXJjZS1tYXBwZXIudHMiXSwKICAibWFwcGluZ3MiOiAiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSw2QkFBdUI7QUF3QnZCLHNCQUNDLE9BQ0EsT0FDQSxLQUNDO0FBQ0QsTUFBSSxBQUFNLFFBQU47QUFBVyxVQUFNO0FBQ3JCLFFBQU0sUUFBUSxJQUFJLGFBQWEsT0FBUSxNQUFNLE1BQU0sT0FBTyxPQUFrQjtBQUM1R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3
-
4
- type LineChar = ts.LineAndCharacter;
5
-
6
- export type FileMapping = LineMapping[];
7
-
8
- type LineMapping = CharacterMapping[]; // FileMapping[generated_line_index] = LineMapping
9
-
10
- type CharacterMapping = [
11
- number, // generated character
12
- number, // original file
13
- number, // original line
14
- number // original index
15
- ];
16
-
17
- type ReorderedChar = [original_character: number, generated_line: number, generated_character: number];
18
-
19
- interface ReorderedMap {
20
- [original_line: number]: ReorderedChar[];
21
- }
22
-
23
- function binaryInsert(array: number[], value: number): void;
24
- function binaryInsert<T extends Record<any, number> | number[]>(array: T[], value: T, key: keyof T): void;
25
- function binaryInsert<A extends Array<Record<any, number>> | number[]>(
26
- array: A,
27
- value: A[any],
28
- key?: keyof (A[any] & object)
29
- ) {
30
- if (0 === key) key = '0' as keyof A[any];
31
- const index = 1 + binarySearch(array, (key ? value[key] : value) as number, key);
32
- let i = array.length;
33
- while (index !== i--) array[1 + i] = array[i];
34
- array[index] = value;
35
- }
36
-
37
- function binarySearch<T extends object | number>(array: T[], target: number, key?: keyof (T & object)) {
38
- if (!array || 0 === array.length) return -1;
39
- if (0 === key) key = '0' as keyof T;
40
- let low = 0;
41
- let high = array.length - 1;
42
- while (low <= high) {
43
- const i = low + ((high - low) >> 1);
44
- const item = undefined === key ? array[i] : array[i][key];
45
- if (item === target) return i;
46
- if (item < target) low = i + 1;
47
- else high = i - 1;
48
- }
49
- if ((low = ~low) < 0) low = ~low - 1;
50
- return low;
51
- }
52
-
53
- export class SourceMapper {
54
- private mappings: FileMapping;
55
- private reverseMappings?: ReorderedMap;
56
-
57
- constructor(mappings: FileMapping | string) {
58
- if (typeof mappings === 'string') this.mappings = decode(mappings) as FileMapping;
59
- else this.mappings = mappings;
60
- }
61
-
62
- getOriginalPosition(position: LineChar): LineChar {
63
- const lineMap = this.mappings[position.line];
64
- if (!lineMap) {
65
- return { line: -1, character: -1 };
66
- }
67
-
68
- const closestMatch = binarySearch(lineMap, position.character, 0);
69
- const match = lineMap[closestMatch];
70
- if (!match) {
71
- return { line: -1, character: -1 };
72
- }
73
-
74
- const { 2: line, 3: character } = match;
75
- return { line, character };
76
- }
77
-
78
- getGeneratedPosition(position: LineChar): LineChar {
79
- if (!this.reverseMappings) this.computeReversed();
80
- const lineMap = this.reverseMappings![position.line];
81
- if (!lineMap) {
82
- return { line: -1, character: -1 };
83
- }
84
-
85
- const closestMatch = binarySearch(lineMap, position.character, 0);
86
- const match = lineMap[closestMatch];
87
- if (!match) {
88
- return { line: -1, character: -1 };
89
- }
90
-
91
- const { 1: line, 2: character } = match;
92
- return { line, character };
93
- }
94
-
95
- private computeReversed() {
96
- this.reverseMappings = {} as ReorderedMap;
97
- for (let generated_line = 0; generated_line !== this.mappings.length; generated_line++) {
98
- for (const { 0: generated_index, 2: original_line, 3: original_character_index } of this.mappings[
99
- generated_line
100
- ]) {
101
- const reordered_char: ReorderedChar = [original_character_index, generated_line, generated_index];
102
- if (original_line in this.reverseMappings) binaryInsert(this.reverseMappings[original_line], reordered_char, 0);
103
- else this.reverseMappings[original_line] = [reordered_char];
104
- }
105
- }
106
- }
107
- }