"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 });
const assert = __importStar(require("assert"));
const sinon_1 = __importDefault(require("sinon"));
const vscode_languageserver_1 = require("vscode-languageserver");
const documents_1 = require("../../../src/lib/documents");
const importPackage = __importStar(require("../../../src/importPackage"));
const SvelteDocument_1 = require("../../../src/plugins/svelte/SvelteDocument");
const configLoader_1 = require("../../../src/lib/documents/configLoader");
describe('Svelte Document', () => {
    function getSourceCode(transpiled) {
        return `
        <p>jo</p>
        <script>${transpiled ? '\n' : ''}const a = true</script>
        <h1>Hello, world!</h1>
        <style>.bla {}</style>
        `;
    }
    function setup(config = {}) {
        sinon_1.default.stub(configLoader_1.configLoader, 'getConfig').returns(config);
        const parent = new documents_1.Document('file:///hello.svelte', getSourceCode(false));
        sinon_1.default.restore();
        const svelteDoc = new SvelteDocument_1.SvelteDocument(parent);
        return { parent, svelteDoc };
    }
    it('gets the parents text', () => {
        const { parent, svelteDoc } = setup();
        assert.strictEqual(svelteDoc.getText(), parent.getText());
    });
    describe('#transpiled (fallback)', () => {
        async function setupTranspiledWithStringSourceMap() {
            const stringSourceMapScript = () => ({
                code: '',
                map: JSON.stringify({
                    version: 3,
                    file: '',
                    names: [],
                    sources: [],
                    sourceRoot: '',
                    mappings: ''
                })
            });
            return setupTranspiled(stringSourceMapScript);
        }
        async function setupTranspiledWithObjectSourceMap() {
            const rawObjectSourceMapScript = () => ({
                code: '',
                map: {
                    version: 3,
                    file: '',
                    names: [],
                    sources: [],
                    sourceRoot: '',
                    mappings: ''
                }
            });
            return setupTranspiled(rawObjectSourceMapScript);
        }
        async function setupTranspiledWithClassSourceMap() {
            const rawObjectSourceMapScript = () => ({
                code: '',
                map: {
                    toString: () => JSON.stringify({
                        version: 3,
                        file: '',
                        names: [],
                        sources: [],
                        sourceRoot: '',
                        mappings: ''
                    })
                }
            });
            return setupTranspiled(rawObjectSourceMapScript);
        }
        async function setupTranspiled(sourceMapPreProcessor) {
            const { parent, svelteDoc } = setup({
                preprocess: {
                    script: sourceMapPreProcessor
                }
            });
            // stub svelte preprocess and getOriginalPosition
            // to fake a source mapping process with the fallback version
            sinon_1.default
                .stub(importPackage, 'getPackageInfo')
                .returns({ path: '', version: { full: '', major: 3, minor: 31, patch: 0 } });
            // @ts-ignore
            sinon_1.default.stub(importPackage, 'importSvelte').returns({
                preprocess: (text, preprocessor) => {
                    preprocessor = Array.isArray(preprocessor) ? preprocessor : [preprocessor];
                    preprocessor.forEach((p) => p.script?.({}));
                    return Promise.resolve({
                        code: getSourceCode(true),
                        dependencies: [],
                        toString: () => getSourceCode(true),
                        map: null
                    });
                },
                VERSION: '',
                compile: null,
                parse: null
            });
            const transpiled = await svelteDoc.getTranspiled();
            const scriptSourceMapper = transpiled.scriptMapper.sourceMapper;
            // hacky reset of method because mocking the SourceMap constructor is an impossible task
            scriptSourceMapper.getOriginalPosition = ({ line, character }) => ({
                line: line - 1,
                character
            });
            scriptSourceMapper.getGeneratedPosition = ({ line, character }) => ({
                line: line + 1,
                character
            });
            sinon_1.default.restore();
            return { parent, svelteDoc, transpiled };
        }
        function assertCanMapBackAndForth(transpiled, generatedPosition, originalPosition) {
            assert.deepStrictEqual(transpiled.getOriginalPosition(generatedPosition), originalPosition, 'error mapping to original position');
            assert.deepStrictEqual(transpiled.getGeneratedPosition(originalPosition), generatedPosition, 'error mapping to generated position');
        }
        it('should map correctly within string valued sourcemapped script', async () => {
            const { transpiled } = await setupTranspiledWithStringSourceMap();
            assertCanMapBackAndForth(transpiled, vscode_languageserver_1.Position.create(3, 2), vscode_languageserver_1.Position.create(2, 18));
        });
        it('should map correctly within object valued sourcemapped script', async () => {
            const { transpiled } = await setupTranspiledWithObjectSourceMap();
            assertCanMapBackAndForth(transpiled, vscode_languageserver_1.Position.create(3, 2), vscode_languageserver_1.Position.create(2, 18));
        });
        it('should map correctly within class valued sourcemapped script', async () => {
            const { transpiled } = await setupTranspiledWithClassSourceMap();
            assertCanMapBackAndForth(transpiled, vscode_languageserver_1.Position.create(3, 2), vscode_languageserver_1.Position.create(2, 18));
        });
        it('should map correctly in template before script', async () => {
            const { transpiled } = await setupTranspiledWithStringSourceMap();
            assertCanMapBackAndForth(transpiled, vscode_languageserver_1.Position.create(1, 1), vscode_languageserver_1.Position.create(1, 1));
        });
        it('should map correctly in template after script', async () => {
            const { transpiled } = await setupTranspiledWithStringSourceMap();
            assertCanMapBackAndForth(transpiled, vscode_languageserver_1.Position.create(4, 1), vscode_languageserver_1.Position.create(3, 1));
        });
        it('should map correctly in style', async () => {
            const { transpiled } = await setupTranspiledWithStringSourceMap();
            assertCanMapBackAndForth(transpiled, vscode_languageserver_1.Position.create(5, 18), vscode_languageserver_1.Position.create(4, 18));
        });
    });
});
//# sourceMappingURL=SvelteDocument.test.js.map