typescript-plugin-scoped-imports 0.1.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.
- package/CHANGELOG.md +8 -0
- package/LICENSE +21 -0
- package/README.md +84 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +409 -0
- package/package.json +47 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.1 - 2026-02-13
|
|
4
|
+
|
|
5
|
+
- Fix: alias/private scope validation now resolves canonical module paths, preventing false positives with repeated folder names (e.g. `ScopeTrap`).
|
|
6
|
+
- Tests: expanded `tsserver` integration coverage, including alias in-scope completion and repeated-folder-name protection.
|
|
7
|
+
- Compatibility: Node minimum version aligned to `>=20`.
|
|
8
|
+
- CI: matrix coverage for Node `20` and `24`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nicolas Viotti
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# TypeScript Plugin: Scoped Imports
|
|
2
|
+
|
|
3
|
+
TypeScript Language Server plugin para controlar auto-imports basado en el scope del archivo.
|
|
4
|
+
|
|
5
|
+
## Estado actual
|
|
6
|
+
|
|
7
|
+
Regla validada en esta fase:
|
|
8
|
+
|
|
9
|
+
- `__private__` es accesible desde su carpeta padre y subdirectorios.
|
|
10
|
+
- Fuera de ese subtree, el plugin bloquea sugerencias y fixes que introduzcan imports privados.
|
|
11
|
+
|
|
12
|
+
## Instalacion (workspace)
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pnpm install
|
|
16
|
+
pnpm run build
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Requiere Node.js 20 o superior.
|
|
20
|
+
|
|
21
|
+
## Configuracion
|
|
22
|
+
|
|
23
|
+
En tu `tsconfig.json`:
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
{
|
|
27
|
+
"compilerOptions": {
|
|
28
|
+
"plugins": [
|
|
29
|
+
{
|
|
30
|
+
"name": "typescript-plugin-scoped-imports"
|
|
31
|
+
}
|
|
32
|
+
]
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Convencion: el plugin considera privados los paths que contengan la carpeta `__private__`.
|
|
38
|
+
|
|
39
|
+
## Matriz de validacion
|
|
40
|
+
|
|
41
|
+
La suite automatizada vive en:
|
|
42
|
+
|
|
43
|
+
- `packages/typescript-plugin-scoped-imports/__tests__/integration/tsserver.scoped-imports.spec.ts`
|
|
44
|
+
|
|
45
|
+
| Caso | Esperado | Resultado |
|
|
46
|
+
| --- | --- | --- |
|
|
47
|
+
| Carga del plugin en tsserver | Debe loguear `PLUGIN LOADING` | Automatizado |
|
|
48
|
+
| Path completion out-of-scope (`Home.tsx` + `@/components/gallery/`) | No sugerir `__private__` | Automatizado |
|
|
49
|
+
| Path completion in-scope padre (`ParentComponent.tsx` + `./`) | Sugerir `__private__` | Automatizado |
|
|
50
|
+
| Path completion in-scope descendiente (`silbing/index.tsx` + `../`) | Sugerir `__private__` | Automatizado |
|
|
51
|
+
| Path completion out-of-scope lateral (`UtilsComponent.tsx` + `../gallery/`) | No sugerir `__private__` | Automatizado |
|
|
52
|
+
| CodeFix missing import out-of-scope (`Home.tsx`) | No proponer imports privados | Automatizado |
|
|
53
|
+
| CodeFix missing import in-scope padre (`ParentComponent.tsx`) | Proponer import privado valido | Automatizado |
|
|
54
|
+
| CodeFix missing import in-scope descendiente (`silbing/nephew/index.tsx`) | Proponer import privado valido | Automatizado |
|
|
55
|
+
| Combined fix out-of-scope (`fixMissingImport`) | Sin cambios con `__private__` | Automatizado |
|
|
56
|
+
| Combined fix in-scope (`fixMissingImport`) | Con cambios privados validos | Automatizado |
|
|
57
|
+
| `getCompletionEntryDetails` bloqueado | Respuesta vacia y log de bloqueo | Automatizado |
|
|
58
|
+
| `getEditsForRefactor` smoke | No romper flujo ni introducir `__private__` fuera de scope | Automatizado |
|
|
59
|
+
| Riesgo alias por nombre repetido (`views/gallery/ScopeTrap.tsx`) | No filtrar incorrectamente por coincidencia de nombre | Automatizado |
|
|
60
|
+
|
|
61
|
+
## Ejecutar validacion automatizada
|
|
62
|
+
|
|
63
|
+
Desde la raiz del workspace:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pnpm run build
|
|
67
|
+
pnpm run test
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Gaps detectados (priorizados)
|
|
71
|
+
|
|
72
|
+
No hay gaps abiertos de severidad alta/media en la matriz actual.
|
|
73
|
+
|
|
74
|
+
## Uso en proyecto de prueba
|
|
75
|
+
|
|
76
|
+
Ver `examples/test-project/` en la raiz del workspace para un ejemplo de consumo real.
|
|
77
|
+
|
|
78
|
+
## Roadmap
|
|
79
|
+
|
|
80
|
+
- [x] Fase 1: POC y validacion de carga
|
|
81
|
+
- [x] Validacion integral de casos de completions y codefixes
|
|
82
|
+
- [ ] Fase 2: Reglas contextuales adicionales
|
|
83
|
+
- [ ] Fase 3: Configuracion flexible
|
|
84
|
+
- [ ] Fase 4: Distribucion y documentacion completa
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
6
|
+
const PRIVATE_FOLDER = "__private__";
|
|
7
|
+
const PRIVATE_SEGMENT = `/${PRIVATE_FOLDER}/`;
|
|
8
|
+
const PRIVATE_SEGMENT_START = `/${PRIVATE_FOLDER}`;
|
|
9
|
+
const PRIVATE_FOLDER_REGEX = PRIVATE_FOLDER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
10
|
+
const PRIVATE_IMPORT_PATTERN = new RegExp(`from\\s+["']([^"']*${PRIVATE_FOLDER_REGEX}[^"']*)["']`, "g");
|
|
11
|
+
function init(modules) {
|
|
12
|
+
function create(info) {
|
|
13
|
+
info.project.projectService.logger.info("===================================");
|
|
14
|
+
info.project.projectService.logger.info("PLUGIN LOADING: typescript-plugin-scoped-imports");
|
|
15
|
+
info.project.projectService.logger.info("===================================");
|
|
16
|
+
try {
|
|
17
|
+
const config = info.config || {};
|
|
18
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: Config loaded - ${JSON.stringify(config)}`);
|
|
19
|
+
const tsApi = modules.typescript;
|
|
20
|
+
function normalizePath(value) {
|
|
21
|
+
return value.replace(/\\/g, "/");
|
|
22
|
+
}
|
|
23
|
+
function toDirectoryPath(value) {
|
|
24
|
+
return value.endsWith("/") ? value : `${value}/`;
|
|
25
|
+
}
|
|
26
|
+
function toPosixAbsolute(value) {
|
|
27
|
+
return normalizePath(node_path_1.default.resolve(value));
|
|
28
|
+
}
|
|
29
|
+
function getCompilerOptions() {
|
|
30
|
+
const programOptions = oldLS.getProgram()?.getCompilerOptions();
|
|
31
|
+
if (programOptions) {
|
|
32
|
+
return programOptions;
|
|
33
|
+
}
|
|
34
|
+
return info.project.getCompilerOptions();
|
|
35
|
+
}
|
|
36
|
+
function getProjectBaseDir(compilerOptions) {
|
|
37
|
+
const baseDir = compilerOptions.baseUrl
|
|
38
|
+
? node_path_1.default.resolve(info.project.getCurrentDirectory(), compilerOptions.baseUrl)
|
|
39
|
+
: info.project.getCurrentDirectory();
|
|
40
|
+
return toPosixAbsolute(baseDir);
|
|
41
|
+
}
|
|
42
|
+
function buildPathPatternRegex(pattern) {
|
|
43
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
|
44
|
+
const wildcardRegex = escaped.replace(/\*/g, "(.*)");
|
|
45
|
+
return new RegExp(`^${wildcardRegex}$`);
|
|
46
|
+
}
|
|
47
|
+
function tryResolveWithPathsMapping(modulePath, compilerOptions) {
|
|
48
|
+
const paths = compilerOptions.paths;
|
|
49
|
+
if (!paths) {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
const baseDir = getProjectBaseDir(compilerOptions);
|
|
53
|
+
for (const [pattern, targets] of Object.entries(paths)) {
|
|
54
|
+
const matcher = buildPathPatternRegex(pattern);
|
|
55
|
+
const match = modulePath.match(matcher);
|
|
56
|
+
if (!match) {
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const captures = match.slice(1);
|
|
60
|
+
for (const target of targets) {
|
|
61
|
+
let captureIndex = 0;
|
|
62
|
+
const replaced = target.replace(/\*/g, () => {
|
|
63
|
+
const value = captures[captureIndex] ?? "";
|
|
64
|
+
captureIndex += 1;
|
|
65
|
+
return value;
|
|
66
|
+
});
|
|
67
|
+
const absolute = node_path_1.default.isAbsolute(replaced)
|
|
68
|
+
? toPosixAbsolute(replaced)
|
|
69
|
+
: toPosixAbsolute(node_path_1.default.join(baseDir, replaced));
|
|
70
|
+
return absolute;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
function resolveImportPathToAbsolute(importPath, currentFile) {
|
|
76
|
+
const normalizedImportPath = normalizePath(importPath);
|
|
77
|
+
const normalizedCurrentFile = normalizePath(currentFile);
|
|
78
|
+
if (normalizedImportPath.startsWith(".")) {
|
|
79
|
+
const currentDir = node_path_1.default.dirname(normalizedCurrentFile);
|
|
80
|
+
return toPosixAbsolute(node_path_1.default.resolve(currentDir, normalizedImportPath));
|
|
81
|
+
}
|
|
82
|
+
if (normalizedImportPath.startsWith("/")) {
|
|
83
|
+
return toPosixAbsolute(normalizedImportPath);
|
|
84
|
+
}
|
|
85
|
+
const compilerOptions = getCompilerOptions();
|
|
86
|
+
const host = {
|
|
87
|
+
fileExists: tsApi.sys.fileExists,
|
|
88
|
+
readFile: tsApi.sys.readFile,
|
|
89
|
+
directoryExists: tsApi.sys.directoryExists,
|
|
90
|
+
getDirectories: tsApi.sys.getDirectories,
|
|
91
|
+
realpath: tsApi.sys.realpath,
|
|
92
|
+
};
|
|
93
|
+
const resolved = tsApi.resolveModuleName(normalizedImportPath, normalizedCurrentFile, compilerOptions, host).resolvedModule?.resolvedFileName;
|
|
94
|
+
if (resolved) {
|
|
95
|
+
return normalizePath(resolved);
|
|
96
|
+
}
|
|
97
|
+
return tryResolveWithPathsMapping(normalizedImportPath, compilerOptions);
|
|
98
|
+
}
|
|
99
|
+
function getPrivateParentDirectory(importPath, currentFile) {
|
|
100
|
+
const resolvedImportPath = resolveImportPathToAbsolute(importPath, currentFile);
|
|
101
|
+
if (!resolvedImportPath) {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
const privateSegmentIndex = resolvedImportPath.indexOf(PRIVATE_SEGMENT_START);
|
|
105
|
+
if (privateSegmentIndex === -1) {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
return toDirectoryPath(resolvedImportPath.substring(0, privateSegmentIndex + 1));
|
|
109
|
+
}
|
|
110
|
+
// Helper: Check if a file can access a __private__ folder
|
|
111
|
+
// Rule: A file can access __private__ only if it's in the "scope" of that __private__ folder
|
|
112
|
+
// The scope is: the parent directory of __private__ and all its subdirectories
|
|
113
|
+
function isPrivateImportAllowed(importPath, currentFile) {
|
|
114
|
+
const normalizedImportPath = normalizePath(importPath);
|
|
115
|
+
const normalizedCurrentFile = normalizePath(currentFile);
|
|
116
|
+
// DEBUG: Log all calls to understand what TypeScript sends
|
|
117
|
+
info.project.projectService.logger.info(`[DEBUG isPrivateImportAllowed] importPath="${normalizedImportPath}" currentFile="${normalizedCurrentFile}"`);
|
|
118
|
+
// If import doesn't contain __private__, allow
|
|
119
|
+
if (!normalizedImportPath.includes(PRIVATE_FOLDER)) {
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
// Case 1: Current file is inside __private__ - allow all
|
|
123
|
+
if (normalizedCurrentFile.includes(PRIVATE_SEGMENT)) {
|
|
124
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: ALLOWING (file inside ${PRIVATE_FOLDER}): ${normalizedCurrentFile}`);
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
const privateParentDir = getPrivateParentDirectory(normalizedImportPath, normalizedCurrentFile);
|
|
128
|
+
if (!privateParentDir) {
|
|
129
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING import (cannot resolve private parent): "${normalizedImportPath}" from "${normalizedCurrentFile}"`);
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
const currentFileDir = toDirectoryPath(node_path_1.default.dirname(normalizedCurrentFile));
|
|
133
|
+
if (currentFileDir.startsWith(privateParentDir)) {
|
|
134
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: ALLOWING import (in scope): "${normalizedImportPath}" from "${normalizedCurrentFile}"`);
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING import (out of scope): "${normalizedImportPath}" from "${normalizedCurrentFile}"`);
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
// Helper: Extract import paths containing __private__ from text changes
|
|
141
|
+
function extractPrivateImportPaths(changes) {
|
|
142
|
+
const paths = [];
|
|
143
|
+
const importPattern = new RegExp(PRIVATE_IMPORT_PATTERN.source, PRIVATE_IMPORT_PATTERN.flags);
|
|
144
|
+
for (const change of changes) {
|
|
145
|
+
for (const textChange of change.textChanges || []) {
|
|
146
|
+
const newText = textChange.newText;
|
|
147
|
+
if (!newText)
|
|
148
|
+
continue;
|
|
149
|
+
// Reset regex state
|
|
150
|
+
importPattern.lastIndex = 0;
|
|
151
|
+
let match = importPattern.exec(newText);
|
|
152
|
+
while (match !== null) {
|
|
153
|
+
paths.push(match[1]);
|
|
154
|
+
match = importPattern.exec(newText);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return paths;
|
|
159
|
+
}
|
|
160
|
+
// Helper: Check if changes contain blocked private imports for a given file
|
|
161
|
+
function hasBlockedPrivateImports(changes, currentFile) {
|
|
162
|
+
const privatePaths = extractPrivateImportPaths(changes);
|
|
163
|
+
return privatePaths.some((path) => !isPrivateImportAllowed(path, currentFile));
|
|
164
|
+
}
|
|
165
|
+
// Helper: Simple check if changes contain any __private__ import
|
|
166
|
+
function containsPrivateImport(changes) {
|
|
167
|
+
return changes.some((change) => change.textChanges?.some((textChange) => {
|
|
168
|
+
const newText = textChange.newText;
|
|
169
|
+
return newText?.includes(PRIVATE_FOLDER) ?? false;
|
|
170
|
+
}));
|
|
171
|
+
}
|
|
172
|
+
// Create language service proxy
|
|
173
|
+
const proxy = Object.create(null);
|
|
174
|
+
const proxyObject = proxy;
|
|
175
|
+
const oldLS = info.languageService;
|
|
176
|
+
// Copy all methods from original LS
|
|
177
|
+
for (const k in oldLS) {
|
|
178
|
+
const key = k;
|
|
179
|
+
const x = oldLS[key];
|
|
180
|
+
if (typeof x === "function") {
|
|
181
|
+
proxyObject[k] = (...args) => x.apply(oldLS, args);
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
proxyObject[k] = x;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
// Helper: Extract the import path being typed at the given position
|
|
188
|
+
function getImportPathAtPosition(fileName, position) {
|
|
189
|
+
try {
|
|
190
|
+
const program = oldLS.getProgram();
|
|
191
|
+
if (!program)
|
|
192
|
+
return null;
|
|
193
|
+
const sourceFile = program.getSourceFile(fileName);
|
|
194
|
+
if (!sourceFile)
|
|
195
|
+
return null;
|
|
196
|
+
const text = sourceFile.getFullText();
|
|
197
|
+
// Find the string literal containing the position
|
|
198
|
+
// Look backwards from position to find the opening quote
|
|
199
|
+
let start = position - 1;
|
|
200
|
+
while (start >= 0 && text[start] !== '"' && text[start] !== "'") {
|
|
201
|
+
start--;
|
|
202
|
+
}
|
|
203
|
+
if (start < 0)
|
|
204
|
+
return null;
|
|
205
|
+
const quote = text[start];
|
|
206
|
+
// Extract the path from after the quote to the position
|
|
207
|
+
const path = text.substring(start + 1, position);
|
|
208
|
+
return path;
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
// Helper: Check if a typed path prefix allows access to __private__
|
|
215
|
+
function isPathPrefixValidForPrivate(pathPrefix, currentFile) {
|
|
216
|
+
const normalizedPath = pathPrefix.replace(/\\/g, "/");
|
|
217
|
+
if (!normalizedPath) {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
let basePath = normalizedPath;
|
|
221
|
+
if (basePath === ".") {
|
|
222
|
+
basePath = "./";
|
|
223
|
+
}
|
|
224
|
+
else if (basePath === "..") {
|
|
225
|
+
basePath = "../";
|
|
226
|
+
}
|
|
227
|
+
if (!basePath.endsWith("/")) {
|
|
228
|
+
basePath += "/";
|
|
229
|
+
}
|
|
230
|
+
const candidateImportPath = `${basePath}${PRIVATE_FOLDER}`;
|
|
231
|
+
return isPrivateImportAllowed(candidateImportPath, currentFile);
|
|
232
|
+
}
|
|
233
|
+
// Intercept getCompletionsAtPosition
|
|
234
|
+
proxy.getCompletionsAtPosition = (fileName, position, options) => {
|
|
235
|
+
const prior = oldLS.getCompletionsAtPosition(fileName, position, options);
|
|
236
|
+
if (!prior) {
|
|
237
|
+
return prior;
|
|
238
|
+
}
|
|
239
|
+
info.project.projectService.logger.info(`[DEBUG getCompletionsAtPosition] fileName="${fileName}" entries=${prior.entries.length}`);
|
|
240
|
+
const originalCount = prior.entries.length;
|
|
241
|
+
// Get the path being typed (for directory completion validation)
|
|
242
|
+
const typedPath = getImportPathAtPosition(fileName, position);
|
|
243
|
+
info.project.projectService.logger.info(`[DEBUG] typedPath="${typedPath}"`);
|
|
244
|
+
// Log entries that contain __private__ for debugging
|
|
245
|
+
for (const entry of prior.entries) {
|
|
246
|
+
if (entry.name?.includes(PRIVATE_FOLDER) ||
|
|
247
|
+
entry.source?.includes(PRIVATE_FOLDER) ||
|
|
248
|
+
entry.sourceDisplay?.some((p) => p.text.includes(PRIVATE_FOLDER))) {
|
|
249
|
+
info.project.projectService.logger.info(`[DEBUG entry] name="${entry.name}" source="${entry.source}" kind="${entry.kind}" sourceDisplay="${entry.sourceDisplay?.map((p) => p.text).join("")}"`);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
// Find blocked names (from __private__ sources that are not allowed)
|
|
253
|
+
const blockedNames = new Set();
|
|
254
|
+
for (const entry of prior.entries) {
|
|
255
|
+
const source = entry.source;
|
|
256
|
+
if (source?.includes(PRIVATE_FOLDER)) {
|
|
257
|
+
if (!isPrivateImportAllowed(source, fileName)) {
|
|
258
|
+
blockedNames.add(entry.name);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
// Filter entries
|
|
263
|
+
const filteredEntries = prior.entries.filter((entry) => {
|
|
264
|
+
// Handle entries with __private__ in the name (usually directory suggestions)
|
|
265
|
+
if (entry.name?.toLowerCase().includes(PRIVATE_FOLDER)) {
|
|
266
|
+
// If there's a source, use isPrivateImportAllowed
|
|
267
|
+
if (entry.source) {
|
|
268
|
+
return isPrivateImportAllowed(entry.source, fileName);
|
|
269
|
+
}
|
|
270
|
+
// No source - this is a directory suggestion in path completion
|
|
271
|
+
if (entry.kind === "directory") {
|
|
272
|
+
// Check if the typed path allows access to __private__
|
|
273
|
+
if (typedPath !== null &&
|
|
274
|
+
isPathPrefixValidForPrivate(typedPath, fileName)) {
|
|
275
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: ALLOWING ${PRIVATE_FOLDER} directory (valid path: "${typedPath}")`);
|
|
276
|
+
return true;
|
|
277
|
+
}
|
|
278
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING ${PRIVATE_FOLDER} directory (invalid path: "${typedPath}")`);
|
|
279
|
+
return false;
|
|
280
|
+
}
|
|
281
|
+
// For other kinds without source, block
|
|
282
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING entry by name (no source): ${entry.name}`);
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
285
|
+
// Block directories that match blocked import sources
|
|
286
|
+
if (entry.kind === "directory" && blockedNames.has(entry.name)) {
|
|
287
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING directory: ${entry.name}`);
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
// If no source, check other fields for __private__
|
|
291
|
+
if (!entry.source) {
|
|
292
|
+
const entryText = (entry.name +
|
|
293
|
+
(entry.insertText || "") +
|
|
294
|
+
(entry.sourceDisplay?.map((p) => p.text).join("") || "") +
|
|
295
|
+
JSON.stringify(entry.data || {})).toLowerCase();
|
|
296
|
+
if (entryText.includes(PRIVATE_FOLDER)) {
|
|
297
|
+
// Try to extract a path from sourceDisplay to validate
|
|
298
|
+
const sourceDisplayText = entry.sourceDisplay?.map((p) => p.text).join("") || "";
|
|
299
|
+
if (sourceDisplayText.includes(PRIVATE_FOLDER)) {
|
|
300
|
+
// Use sourceDisplay as the import path for validation
|
|
301
|
+
return isPrivateImportAllowed(sourceDisplayText, fileName);
|
|
302
|
+
}
|
|
303
|
+
// Can't determine scope, block to be safe
|
|
304
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING entry without source: ${entry.name} (${entryText})`);
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
return true;
|
|
308
|
+
}
|
|
309
|
+
// Check source path
|
|
310
|
+
const source = entry.source;
|
|
311
|
+
if (source?.includes(PRIVATE_FOLDER)) {
|
|
312
|
+
return isPrivateImportAllowed(source, fileName);
|
|
313
|
+
}
|
|
314
|
+
return true;
|
|
315
|
+
});
|
|
316
|
+
const filteredCount = filteredEntries.length;
|
|
317
|
+
if (originalCount !== filteredCount) {
|
|
318
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: Filtered ${originalCount - filteredCount} completions (${originalCount} -> ${filteredCount})`);
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
...prior,
|
|
322
|
+
entries: filteredEntries,
|
|
323
|
+
};
|
|
324
|
+
};
|
|
325
|
+
// Intercept getCompletionEntryDetails
|
|
326
|
+
proxy.getCompletionEntryDetails = (fileName, position, entryName, formatOptions, source, preferences, data) => {
|
|
327
|
+
if (source?.includes(PRIVATE_FOLDER)) {
|
|
328
|
+
if (!isPrivateImportAllowed(source, fileName)) {
|
|
329
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING completion details for source: ${source}`);
|
|
330
|
+
return undefined;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return oldLS.getCompletionEntryDetails(fileName, position, entryName, formatOptions, source, preferences, data);
|
|
334
|
+
};
|
|
335
|
+
// Intercept getCodeFixesAtPosition
|
|
336
|
+
proxy.getCodeFixesAtPosition = (fileName, start, end, errorCodes, formatOptions, preferences) => {
|
|
337
|
+
const fixes = oldLS.getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences);
|
|
338
|
+
const filteredFixes = fixes.filter((fix) => {
|
|
339
|
+
if (containsPrivateImport(fix.changes)) {
|
|
340
|
+
if (hasBlockedPrivateImports(fix.changes, fileName)) {
|
|
341
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING code fix "${fix.fixName}"`);
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return true;
|
|
346
|
+
});
|
|
347
|
+
if (fixes.length !== filteredFixes.length) {
|
|
348
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: Filtered ${fixes.length - filteredFixes.length} code fixes`);
|
|
349
|
+
}
|
|
350
|
+
return filteredFixes;
|
|
351
|
+
};
|
|
352
|
+
// Intercept getCombinedCodeFix
|
|
353
|
+
proxy.getCombinedCodeFix = (scope, fixId, formatOptions, preferences) => {
|
|
354
|
+
const getCombinedCodeFix = oldLS.getCombinedCodeFix;
|
|
355
|
+
const result = getCombinedCodeFix(scope, fixId, formatOptions, preferences);
|
|
356
|
+
const fileName = scope.fileName;
|
|
357
|
+
const filteredChanges = result.changes.filter((change) => {
|
|
358
|
+
if (containsPrivateImport([change])) {
|
|
359
|
+
if (hasBlockedPrivateImports([change], fileName)) {
|
|
360
|
+
info.project.projectService.logger.info("typescript-plugin-scoped-imports: BLOCKING combined fix change");
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return true;
|
|
365
|
+
});
|
|
366
|
+
if (result.changes.length !== filteredChanges.length) {
|
|
367
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: Filtered ${result.changes.length - filteredChanges.length} combined fix changes`);
|
|
368
|
+
}
|
|
369
|
+
return {
|
|
370
|
+
...result,
|
|
371
|
+
changes: filteredChanges,
|
|
372
|
+
};
|
|
373
|
+
};
|
|
374
|
+
// Intercept getEditsForRefactor
|
|
375
|
+
proxy.getEditsForRefactor = (fileName, formatOptions, positionOrRange, refactorName, actionName, preferences, interactiveRefactorArguments) => {
|
|
376
|
+
const result = oldLS.getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences, interactiveRefactorArguments);
|
|
377
|
+
if (!result) {
|
|
378
|
+
return result;
|
|
379
|
+
}
|
|
380
|
+
const filteredEdits = result.edits.filter((edit) => {
|
|
381
|
+
if (containsPrivateImport([edit])) {
|
|
382
|
+
if (hasBlockedPrivateImports([edit], fileName)) {
|
|
383
|
+
info.project.projectService.logger.info("typescript-plugin-scoped-imports: BLOCKING refactor edit");
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return true;
|
|
388
|
+
});
|
|
389
|
+
if (result.edits.length !== filteredEdits.length) {
|
|
390
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: Filtered ${result.edits.length - filteredEdits.length} refactor edits`);
|
|
391
|
+
}
|
|
392
|
+
return {
|
|
393
|
+
...result,
|
|
394
|
+
edits: filteredEdits,
|
|
395
|
+
};
|
|
396
|
+
};
|
|
397
|
+
info.project.projectService.logger.info("typescript-plugin-scoped-imports: Plugin proxy created successfully");
|
|
398
|
+
info.project.projectService.logger.info("===================================");
|
|
399
|
+
return proxy;
|
|
400
|
+
}
|
|
401
|
+
catch (error) {
|
|
402
|
+
info.project.projectService.logger.info(`typescript-plugin-scoped-imports: ERROR loading plugin: ${error}`);
|
|
403
|
+
info.project.projectService.logger.info("===================================");
|
|
404
|
+
throw error;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return { create };
|
|
408
|
+
}
|
|
409
|
+
module.exports = init;
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "typescript-plugin-scoped-imports",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "TypeScript Language Server plugin para controlar auto-imports basado en scope",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist",
|
|
9
|
+
"README.md",
|
|
10
|
+
"LICENSE",
|
|
11
|
+
"CHANGELOG.md"
|
|
12
|
+
],
|
|
13
|
+
"keywords": [
|
|
14
|
+
"typescript",
|
|
15
|
+
"plugin",
|
|
16
|
+
"imports",
|
|
17
|
+
"scoped"
|
|
18
|
+
],
|
|
19
|
+
"author": "Nicolas Viotti",
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=20"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@types/node": "^20.0.0",
|
|
26
|
+
"typescript": "^5.0.0",
|
|
27
|
+
"jest": "^29.0.0",
|
|
28
|
+
"@types/jest": "^29.0.0",
|
|
29
|
+
"ts-jest": "^29.0.0",
|
|
30
|
+
"@biomejs/biome": "^1.8.3"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"typescript": ">=4.0.0"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "tsc",
|
|
37
|
+
"typecheck": "tsc --noEmit",
|
|
38
|
+
"watch": "tsc --watch",
|
|
39
|
+
"test": "jest",
|
|
40
|
+
"biome:lint": "biome lint .",
|
|
41
|
+
"biome:lint:fix": "biome lint --write .",
|
|
42
|
+
"biome:format": "biome format .",
|
|
43
|
+
"biome:format:fix": "biome format --write .",
|
|
44
|
+
"biome:check": "biome check .",
|
|
45
|
+
"biome:check:fix": "biome check --write ."
|
|
46
|
+
}
|
|
47
|
+
}
|