-
Notifications
You must be signed in to change notification settings - Fork 12.5k
/
createPlaygroundBuild.js
322 lines (280 loc) · 11.7 KB
/
createPlaygroundBuild.js
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// @ts-check
// This script does two things:
//
// - Listens to changes to the built version of TypeScript (via a filewatcher on `built/local/typescriptServices.js`)
// these trigger creating monaco-typescript compatible builds of TypeScript at `internal/lib/typescriptServices.js§
//
// - Creates a HTTP server which the playground uses. The webserver almost exclusively re-directs requests to
// the latest stable version of monaco-typescript, but specifically overrides requests for the TypeScript js
// file to the version created in the above step.
//
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const path = require('path');
const fs = require('fs');
const child_process = require('child_process');
const http = require('http');
const url = require('url');
function updateTSDist() {
// This code is a direct port of a script from monaco-typescript
// https://github.com/microsoft/monaco-typescript/blob/master/scripts/importTypescript.js
// Currently based on 778ace1 on Apr 25 2020
const generatedNote = `//
// **NOTE**: Do not edit directly! This file is generated using \`npm run import-typescript\`
//
`;
const TYPESCRIPT_LIB_SOURCE = path.join(__dirname, '../built/local');
const TYPESCRIPT_LIB_DESTINATION = path.join(__dirname, '../internal/lib');
(function () {
try {
fs.statSync(TYPESCRIPT_LIB_DESTINATION);
} catch (err) {
fs.mkdirSync(TYPESCRIPT_LIB_DESTINATION);
}
importLibs();
const npmLsOutput = JSON.parse(child_process.execSync("npm ls typescript --depth=0 --json=true").toString());
const typeScriptDependencyVersion = npmLsOutput.dependencies.typescript.version;
fs.writeFileSync(
path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServicesMetadata.ts'),
`${generatedNote}
export const typescriptVersion = "${typeScriptDependencyVersion}";\n`
);
var tsServices = fs.readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.js')).toString();
// Ensure we never run into the node system...
// (this also removes require calls that trick webpack into shimming those modules...)
tsServices = (
tsServices.replace(/\n ts\.sys =([^]*)\n \}\)\(\);/m, `\n // MONACOCHANGE\n ts.sys = undefined;\n // END MONACOCHANGE`)
);
// Eliminate more require() calls...
tsServices = tsServices.replace(/^( +)etwModule = require\(.*$/m, '$1// MONACOCHANGE\n$1etwModule = undefined;\n$1// END MONACOCHANGE');
tsServices = tsServices.replace(/^( +)var result = ts\.sys\.require\(.*$/m, '$1// MONACOCHANGE\n$1var result = undefined;\n$1// END MONACOCHANGE');
// Flag any new require calls (outside comments) so they can be corrected preemptively.
// To avoid missing cases (or using an even more complex regex), temporarily remove comments
// about require() and then check for lines actually calling require().
// \/[*/] matches the start of a comment (single or multi-line).
// ^\s+\*[^/] matches (presumably) a later line of a multi-line comment.
const tsServicesNoCommentedRequire = tsServices.replace(/(\/[*/]|^\s+\*[^/]).*\brequire\(.*/gm, '');
const linesWithRequire = tsServicesNoCommentedRequire.match(/^.*?\brequire\(.*$/gm)
// Allow error messages to include references to require() in their strings
const runtimeRequires = linesWithRequire && linesWithRequire.filter(l => !l.includes(": diag("))
if (runtimeRequires && runtimeRequires.length) {
console.error('Found new require() calls on the following lines. These should be removed to avoid breaking webpack builds.\n');
console.error(linesWithRequire.join('\n'));
process.exit(1);
}
// Make sure process.args don't get called in the browser, this
// should only happen in TS 2.6.2
const beforeProcess = `ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(process.argv));`
const afterProcess = `// MONACOCHANGE\n ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify([]));\n// END MONACOCHANGE`
tsServices = tsServices.replace(beforeProcess, afterProcess);
var tsServices_amd = generatedNote + tsServices +
`
// MONACOCHANGE
// Defining the entire module name because r.js has an issue and cannot bundle this file
// correctly with an anonymous define call
define("vs/language/typescript/lib/typescriptServices", [], function() { return ts; });
// END MONACOCHANGE
`;
fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices-amd.js'), tsServices_amd);
var tsServices_esm = generatedNote + tsServices +
`
// MONACOCHANGE
export var createClassifier = ts.createClassifier;
export var createLanguageService = ts.createLanguageService;
export var displayPartsToString = ts.displayPartsToString;
export var EndOfLineState = ts.EndOfLineState;
export var flattenDiagnosticMessageText = ts.flattenDiagnosticMessageText;
export var IndentStyle = ts.IndentStyle;
export var ScriptKind = ts.ScriptKind;
export var ScriptTarget = ts.ScriptTarget;
export var TokenClass = ts.TokenClass;
// END MONACOCHANGE
`;
fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.js'), tsServices_esm);
var dtsServices = fs.readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.d.ts')).toString();
dtsServices +=
`
// MONACOCHANGE
export = ts;
// END MONACOCHANGE
`;
fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.d.ts'), generatedNote + dtsServices);
})();
function importLibs() {
function getFileName(name) {
return (name === '' ? 'lib.d.ts' : `lib.${name}.d.ts`);
}
function getVariableName(name) {
return (name === '' ? 'lib_dts' : `lib_${name.replace(/\./g, '_')}_dts`);
}
function readLibFile(name) {
var srcPath = path.join(TYPESCRIPT_LIB_SOURCE, getFileName(name));
return fs.readFileSync(srcPath).toString();
}
var queue = [];
var in_queue = {};
var enqueue = function (name) {
if (in_queue[name]) {
return;
}
in_queue[name] = true;
queue.push(name);
};
enqueue('');
enqueue('es2015');
var result = [];
while (queue.length > 0) {
var name = queue.shift();
var contents = readLibFile(name);
var lines = contents.split(/\r\n|\r|\n/);
var output = '';
var writeOutput = function (text) {
if (output.length === 0) {
output = text;
} else {
output += ` + ${text}`;
}
};
var outputLines = [];
var flushOutputLines = function () {
writeOutput(`"${escapeText(outputLines.join('\n'))}"`);
outputLines = [];
};
var deps = [];
for (let i = 0; i < lines.length; i++) {
let m = lines[i].match(/\/\/\/\s*<reference\s*lib="([^"]+)"/);
if (m) {
flushOutputLines();
writeOutput(getVariableName(m[1]));
deps.push(getVariableName(m[1]));
enqueue(m[1]);
continue;
}
outputLines.push(lines[i]);
}
flushOutputLines();
result.push({
name: getVariableName(name),
deps: deps,
output: output
});
}
var strResult = `/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
${generatedNote}`;
// Do a topological sort
while (result.length > 0) {
for (let i = result.length - 1; i >= 0; i--) {
if (result[i].deps.length === 0) {
// emit this node
strResult += `\nexport const ${result[i].name}: string = ${result[i].output};\n`;
// mark dep as resolved
for (let j = 0; j < result.length; j++) {
for (let k = 0; k < result[j].deps.length; k++) {
if (result[j].deps[k] === result[i].name) {
result[j].deps.splice(k, 1);
break;
}
}
}
// remove from result
result.splice(i, 1);
break;
}
}
}
strResult += `
/** This is the DTS which is used when the target is ES6 or below */
export const lib_es5_bundled_dts = lib_dts;
/** This is the DTS which is used by default in monaco-typescript, and when the target is 2015 or above */
export const lib_es2015_bundled_dts = lib_es2015_dts + "" + lib_dom_dts + "" + lib_webworker_importscripts_dts + "" + lib_scripthost_dts + "";
`
var dstPath = path.join(TYPESCRIPT_LIB_DESTINATION, 'lib.ts');
fs.writeFileSync(dstPath, strResult);
}
/**
* Escape text such that it can be used in a javascript string enclosed by double quotes (")
*/
function escapeText(text) {
// See http://www.javascriptkit.com/jsref/escapesequence.shtml
var _backspace = '\b'.charCodeAt(0);
var _formFeed = '\f'.charCodeAt(0);
var _newLine = '\n'.charCodeAt(0);
var _nullChar = 0;
var _carriageReturn = '\r'.charCodeAt(0);
var _tab = '\t'.charCodeAt(0);
var _verticalTab = '\v'.charCodeAt(0);
var _backslash = '\\'.charCodeAt(0);
var _doubleQuote = '"'.charCodeAt(0);
var startPos = 0, chrCode, replaceWith = null, resultPieces = [];
for (var i = 0, len = text.length; i < len; i++) {
chrCode = text.charCodeAt(i);
switch (chrCode) {
case _backspace:
replaceWith = '\\b';
break;
case _formFeed:
replaceWith = '\\f';
break;
case _newLine:
replaceWith = '\\n';
break;
case _nullChar:
replaceWith = '\\0';
break;
case _carriageReturn:
replaceWith = '\\r';
break;
case _tab:
replaceWith = '\\t';
break;
case _verticalTab:
replaceWith = '\\v';
break;
case _backslash:
replaceWith = '\\\\';
break;
case _doubleQuote:
replaceWith = '\\"';
break;
}
if (replaceWith !== null) {
resultPieces.push(text.substring(startPos, i));
resultPieces.push(replaceWith);
startPos = i + 1;
replaceWith = null;
}
}
resultPieces.push(text.substring(startPos, len));
return resultPieces.join('');
}
/// End of import
}
const services = path.join(__dirname, '../built/local/typescriptServices.js');
fs.watchFile(services, () =>{
console.log("Updating the monaco build")
updateTSDist()
})
http.createServer(function (req, res) {
const incoming = url.parse(req.url)
if (incoming.path.endsWith("typescriptServices.js")) {
// Use the built version
res.writeHead(200, {"Content-Type": "text/javascript"});
const amdPath = path.join(__dirname, '../internal/lib/typescriptServices-amd.js');
res.write(fs.readFileSync(amdPath))
} else {
// Redirect to the TS CDN
res.writeHead(302, {
'Location': `https://typescript.azureedge.net/cdn/3.9.2/monaco/${incoming.path}`
});
}
res.end();
}).listen(5615);
console.log("Starting servers\n")
console.log(" - [✓] file watcher: " + services)
console.log(" - [✓] http server: http://localhost:5615")
console.log("\n\nGet started: http://www.staging-typescript.org/play?ts=dev")