"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.relativeNodePath = relativeNodePath;
const lodash_1 = __importDefault(require("lodash"));
const ts = __importStar(require("typescript"));
const debug_1 = __importDefault(require("debug"));
const debugLog = (0, debug_1.default)('ts-autocomplete:log');
const debugTrace = (0, debug_1.default)('ts-autocomplete:trace');
const debugError = (0, debug_1.default)('ts-autocomplete:error');
function relativeNodePath(fileName) {
    const parts = fileName.split(/\/node_modules\//g);
    if (parts.length === 1 && fileName.endsWith('package.json')) {
        return '@mongodb-js/mongodb-ts-autocomplete/package.json';
    }
    return parts[parts.length - 1];
}
function getVirtualLanguageService(fallbackServiceHost) {
    const codeHolder = Object.create(null);
    const versions = Object.create(null);
    const options = {
        target: ts.ScriptTarget.ES2022,
        allowJs: true,
        moduleResolution: ts.ModuleResolutionKind.NodeNext,
        types: [],
        lib: ['es2023'],
        allowImportingTsExtensions: true,
    };
    const updateCode = (newDef) => {
        for (const [key, value] of Object.entries(newDef)) {
            codeHolder[key] = value;
            versions[key] = (versions[key] ?? 0) + 1;
        }
    };
    const listFiles = () => {
        return Object.keys(codeHolder);
    };
    const serviceHost = {
        getScriptFileNames: () => {
            return Object.keys(codeHolder);
        },
        getScriptVersion: (fileName) => {
            fileName = relativeNodePath(fileName);
            return (versions[fileName] ?? 1).toString();
        },
        getScriptSnapshot: (fileName) => {
            const relativeFileName = relativeNodePath(fileName);
            if (relativeFileName in codeHolder) {
                const code = typeof codeHolder[relativeFileName] === 'string'
                    ? codeHolder[relativeFileName]
                    : '';
                return ts.ScriptSnapshot.fromString(code);
            }
            if (fallbackServiceHost) {
                return fallbackServiceHost.getScriptSnapshot(fileName);
            }
        },
        getCurrentDirectory: () => process.cwd(),
        getCompilationSettings: () => options,
        getDefaultLibFileName: (options) => {
            return ts.getDefaultLibFilePath(options);
        },
        fileExists: (fileName) => {
            const relativeFileName = relativeNodePath(fileName);
            if (relativeFileName in codeHolder) {
                return true;
            }
            if (fallbackServiceHost) {
                return fallbackServiceHost.fileExists(fileName);
            }
            return false;
        },
        readFile: (fileName) => {
            const relativeFileName = relativeNodePath(fileName);
            if (relativeFileName in codeHolder) {
                const code = typeof codeHolder[relativeFileName] === 'string'
                    ? codeHolder[relativeFileName]
                    : undefined;
                return code;
            }
            if (fallbackServiceHost) {
                return fallbackServiceHost.readFile(fileName);
            }
        },
        readDirectory: (...args) => {
            return fallbackServiceHost?.readDirectory?.(...args) ?? [];
        },
        directoryExists: (...args) => {
            return fallbackServiceHost?.directoryExists?.(...args) ?? true;
        },
        getDirectories: (...args) => {
            return fallbackServiceHost?.getDirectories?.(...args) ?? [];
        },
        log: (...args) => debugLog(args),
        trace: (...args) => debugTrace(args),
        error: (...args) => debugError(args),
    };
    return {
        languageService: ts.createLanguageService(serviceHost, ts.createDocumentRegistry()),
        updateCode,
        listFiles,
    };
}
function compileSourceFile(code) {
    return ts.createSourceFile('_initial_parsing.ts', code, ts.ScriptTarget.Latest, true);
}
function getSymbolAtPosition(sourceFile, position) {
    function findNodeAtPosition(node) {
        if (position >= node.getStart(sourceFile) && position <= node.getEnd()) {
            return ts.forEachChild(node, findNodeAtPosition) || node;
        }
        return undefined;
    }
    let node = findNodeAtPosition(sourceFile);
    while (node && !ts.isIdentifier(node)) {
        if (node.parent) {
            node = node.parent;
        }
        else {
            break;
        }
    }
    return node && ts.isIdentifier(node) ? node.getText(sourceFile) : null;
}
function mapCompletions(filter, prefix, trigger, completions) {
    return completions.entries
        .filter((entry) => filter({ trigger, kind: entry.kind, name: entry.name }))
        .map((entry) => {
        const result = entry.insertText
            ? prefix.slice(0, -1) + entry.insertText
            : prefix + entry.name;
        return {
            result,
            name: entry.name,
            kind: entry.kind,
        };
    });
}
function filterDiagnostics(diagnostics) {
    return diagnostics.map((item) => {
        const result = {
            ...lodash_1.default.pick(item.file, 'fileName', 'text'),
            ...lodash_1.default.pick(item, 'messageText'),
        };
        delete result.text;
        return result;
    });
}
class Autocompleter {
    filter;
    languageService;
    updateCode;
    listFiles;
    constructor({ filter, fallbackServiceHost } = {}) {
        this.filter = filter ?? (() => true);
        ({
            languageService: this.languageService,
            updateCode: this.updateCode,
            listFiles: this.listFiles,
        } = getVirtualLanguageService(fallbackServiceHost));
    }
    autocomplete(code) {
        this.updateCode({
            '/main.ts': code,
        });
        const completions = this.languageService.getCompletionsAtPosition('/main.ts', code.length, {
            allowIncompleteCompletions: true,
            includeCompletionsWithInsertText: true,
        });
        if (debugLog.enabled) {
            for (const filename of this.listFiles()) {
                if (filename.startsWith('/')) {
                    this.debugLanguageService(filename, 'getSyntacticDiagnostics');
                    this.debugLanguageService(filename, 'getSemanticDiagnostics');
                }
            }
        }
        if (completions) {
            const tsAst = compileSourceFile(code);
            const symbolAtPosition = getSymbolAtPosition(tsAst, code.length) ?? '';
            const prefix = code.slice(0, code.length - symbolAtPosition.length);
            return mapCompletions(this.filter, prefix, symbolAtPosition, completions);
        }
        return [];
    }
    debugLanguageService(filename, method) {
        try {
            debugLog(method, filename, filterDiagnostics(this.languageService[method](filename)));
        }
        catch (err) {
            debugLog(method, filename, err.stack, err.ProgramFiles);
        }
    }
}
exports.default = Autocompleter;
//# sourceMappingURL=index.js.map