File: buildProtocol.mjs

package info (click to toggle)
node-typescript 4.9.5%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 533,908 kB
  • sloc: javascript: 2,018,330; makefile: 7; sh: 1
file content (260 lines) | stat: -rw-r--r-- 10,115 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import ts from "../lib/typescript.js";
import path from "path";
import assert from "assert";

/**
 *
 * @param {string} s
 * @param {string} suffix
 * @returns {boolean}
 */
function endsWith(s, suffix) {
    return s.lastIndexOf(suffix, s.length - suffix.length) !== -1;
}

/**
 * @param {ts.EnumDeclaration} declaration
 * @returns {boolean}
 */
function isStringEnum(declaration) {
    return !!declaration.members.length && declaration.members.every(m => !!m.initializer && m.initializer.kind === ts.SyntaxKind.StringLiteral);
}

class DeclarationsWalker {
    /**
     * @type {ts.Type[]}
     * @private
     */
    visitedTypes = [];
    /**
     * @type {string}
     * @private
     */
    text = "";
    /**
     * @type {ts.Type[]}
     * @private
     */
    removedTypes = [];

    /**
     * @param {ts.TypeChecker} typeChecker
     * @param {ts.SourceFile} protocolFile
     * @private
     */
    constructor(typeChecker, protocolFile) {
        this.typeChecker = typeChecker;
        this.protocolFile = protocolFile;
    }

    /**
     *
     * @param {ts.TypeChecker} typeChecker
     * @param {ts.SourceFile} protocolFile
     * @returns {string}
     */
    static getExtraDeclarations(typeChecker, protocolFile) {
        const walker = new DeclarationsWalker(typeChecker, protocolFile);
        walker.visitTypeNodes(protocolFile);
        let text = walker.text
            ? `declare namespace ts.server.protocol {\n${walker.text}}`
            : "";
        if (walker.removedTypes) {
            text += "\ndeclare namespace ts {\n";
            text += "    // these types are empty stubs for types from services and should not be used directly\n";
            for (const type of walker.removedTypes) {
                text += `    export type ${type.symbol.name} = never;\n`;
            }
            text += "}";
        }
        return text;
    }

    /**
     * @param {ts.Type} type
     * @returns {void}
     * @private
     */
    processType(type) {
        if (this.visitedTypes.indexOf(type) >= 0) {
            return;
        }
        this.visitedTypes.push(type);
        const s = type.aliasSymbol || type.getSymbol();
        if (!s) {
            return;
        }
        if (s.name === "Array" || s.name === "ReadOnlyArray") {
            // we should process type argument instead
            return this.processType(/** @type {any} */(type).typeArguments[0]);
        }
        else {
            const declarations = s.getDeclarations();
            if (declarations) {
                for (const decl of declarations) {
                    const sourceFile = decl.getSourceFile();
                    if (sourceFile === this.protocolFile || /lib(\..+)?\.d.ts/.test(path.basename(sourceFile.fileName))) {
                        return;
                    }
                    if (ts.isEnumDeclaration(decl) && !isStringEnum(decl)) {
                        this.removedTypes.push(type);
                        return;
                    }
                    else {
                        // splice declaration in final d.ts file
                        const text = decl.getFullText();
                        this.text += `${text}\n`;
                        // recursively pull all dependencies into result dts file

                        this.visitTypeNodes(decl);
                    }
                }
            }
        }
    }

    /**
     * @param {ts.Node} node
     * @private
     */
    visitTypeNodes(node) {
        if (node.parent) {
            switch (node.parent.kind) {
                case ts.SyntaxKind.VariableDeclaration:
                case ts.SyntaxKind.MethodDeclaration:
                case ts.SyntaxKind.MethodSignature:
                case ts.SyntaxKind.PropertyDeclaration:
                case ts.SyntaxKind.PropertySignature:
                case ts.SyntaxKind.Parameter:
                case ts.SyntaxKind.IndexSignature:
                    const parent = /** @type {ts.VariableDeclaration | ts.MethodDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration | ts.PropertySignature | ts.MethodSignature | ts.IndexSignatureDeclaration} */ (node.parent);
                    if (parent.type === node) {
                        this.processTypeOfNode(node);
                    }
                    break;
                case ts.SyntaxKind.InterfaceDeclaration:
                    const heritageClauses = /** @type {ts.InterfaceDeclaration} */ (node.parent).heritageClauses;
                    if (heritageClauses) {
                        if (heritageClauses[0].token !== ts.SyntaxKind.ExtendsKeyword) {
                            throw new Error(`Unexpected kind of heritage clause: ${ts.SyntaxKind[heritageClauses[0].kind]}`);
                        }
                        for (const type of heritageClauses[0].types) {
                            this.processTypeOfNode(type);
                        }
                    }
                    break;
            }
        }
        ts.forEachChild(node, n => this.visitTypeNodes(n));
    }

    /**
     * @param {ts.Node} node
     * @private
     */
    processTypeOfNode(node) {
        if (node.kind === ts.SyntaxKind.UnionType) {
            for (const t of /** @type {ts.UnionTypeNode} */ (node).types) {
                this.processTypeOfNode(t);
            }
        }
        else {
            const type = this.typeChecker.getTypeAtLocation(node);
            if (type && !(type.flags & (ts.TypeFlags.TypeParameter))) {
                this.processType(type);
            }
        }
    }
}

/**
 * @param {string} outputFile
 * @param {string} protocolTs
 * @param {string} typeScriptServicesDts
 */
function writeProtocolFile(outputFile, protocolTs, typeScriptServicesDts) {
    /** @type {ts.CompilerOptions} */
    const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: false, types: [], stripInternal: true };

    /**
     * 1st pass - generate a program from protocol.ts and typescriptservices.d.ts and emit core version of protocol.d.ts with all internal members stripped
     * @return text of protocol.d.t.s
     */
    function getInitialDtsFileForProtocol() {
        const program = ts.createProgram([protocolTs, typeScriptServicesDts, path.join(typeScriptServicesDts, "../lib.es5.d.ts")], options);

        /** @type {string | undefined} */
        let protocolDts;
        const emitResult = program.emit(program.getSourceFile(protocolTs), (file, content) => {
            if (endsWith(file, ".d.ts")) {
                protocolDts = content;
            }
        });

        if (protocolDts === undefined) {
            /** @type {ts.FormatDiagnosticsHost} */
            const diagHost = {
                getCanonicalFileName(f) { return f; },
                getCurrentDirectory() { return "."; },
                getNewLine() { return "\r\n"; }
            };
            const diags = emitResult.diagnostics.map(d => ts.formatDiagnostic(d, diagHost)).join("\r\n");
            throw new Error(`Declaration file for protocol.ts is not generated:\r\n${diags}`);
        }
        return protocolDts;
    }

    const protocolFileName = "protocol.d.ts";
    /**
     * Second pass - generate a program from protocol.d.ts and typescriptservices.d.ts, then augment core protocol.d.ts with extra types from typescriptservices.d.ts
     * @param {string} protocolDts
     * @param {boolean} includeTypeScriptServices
     */
    function getProgramWithProtocolText(protocolDts, includeTypeScriptServices) {
        const host = ts.createCompilerHost(options);
        const originalGetSourceFile = host.getSourceFile;
        host.getSourceFile = (fileName) => {
            if (fileName === protocolFileName) {
                assert(options.target !== undefined);
                return ts.createSourceFile(fileName, protocolDts, options.target);
            }
            return originalGetSourceFile.apply(host, [fileName, ts.ScriptTarget.Latest]);
        };
        const rootFiles = includeTypeScriptServices ? [protocolFileName, typeScriptServicesDts] : [protocolFileName];
        return ts.createProgram(rootFiles, options, host);
    }

    let protocolDts = getInitialDtsFileForProtocol();
    const program = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ true);

    const protocolFile = program.getSourceFile("protocol.d.ts");
    assert(protocolFile);
    const extraDeclarations = DeclarationsWalker.getExtraDeclarations(program.getTypeChecker(), protocolFile);
    if (extraDeclarations) {
        protocolDts += extraDeclarations;
    }
    protocolDts += "\nimport protocol = ts.server.protocol;";
    protocolDts += "\nexport = protocol;";
    protocolDts += "\nexport as namespace protocol;";

    // do sanity check and try to compile generated text as standalone program
    const sanityCheckProgram = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ false);
    const diagnostics = [...sanityCheckProgram.getSyntacticDiagnostics(), ...sanityCheckProgram.getSemanticDiagnostics(), ...sanityCheckProgram.getGlobalDiagnostics()];

    ts.sys.writeFile(outputFile, protocolDts);

    if (diagnostics.length) {
        const flattenedDiagnostics = diagnostics.map(d => `${ts.flattenDiagnosticMessageText(d.messageText, "\n")} at ${d.file ? d.file.fileName : "<unknown>"} line ${d.start}`).join("\n");
        throw new Error(`Unexpected errors during sanity check: ${flattenedDiagnostics}`);
    }
}

if (process.argv.length < 5) {
    console.log(`Expected 3 arguments: path to 'protocol.ts', path to 'typescriptservices.d.ts' and path to output file`);
    process.exit(1);
}

const protocolTs = process.argv[2];
const typeScriptServicesDts = process.argv[3];
const outputFile = process.argv[4];
writeProtocolFile(outputFile, protocolTs, typeScriptServicesDts);