Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move to TypeScript 2.6.1 #3559

Merged
merged 24 commits into from Dec 11, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion Jakefile.js
Expand Up @@ -311,7 +311,7 @@ file("built/web/pxtlib.js", [

let ts = fs.readFileSync("node_modules/typescript/lib/typescript.js", "utf8")
ts = ts.replace(/getCompletionsAtPosition: getCompletionsAtPosition,/,
f => f + " " + additionalExports.map(s => s + ": " + s + ",").join(" "))
f => f + " " + additionalExports.map(s => s + ": ts.Completions." + s + ",").join(" "))
fs.writeFileSync("built/web/typescript.js", ts)
})

Expand Down
4 changes: 1 addition & 3 deletions backendutils/backendutils.ts
@@ -1,5 +1,3 @@
/// <reference path="../pxtlib/docsrender.ts"/>

declare var global: any;

global.pxt = pxt;
(global as any).pxt = pxt;
11 changes: 7 additions & 4 deletions cli/buildengine.ts
@@ -1,4 +1,3 @@
/// <reference path="../typings/globals/node/index.d.ts"/>
/// <reference path="../built/pxtlib.d.ts"/>
/// <reference path="../built/pxtsim.d.ts"/>

Expand All @@ -14,7 +13,7 @@ import * as hid from './hid';
import U = pxt.Util;
import Map = pxt.Map;

// abstract over build engine
// abstract over build engine
export interface BuildEngine {
updateEngineAsync: () => Promise<void>;
setPlatformAsync: () => Promise<void>;
Expand Down Expand Up @@ -105,6 +104,10 @@ export const buildEngines: Map<BuildEngine> = {
// once we have a different build engine, set this appropriately
export var thisBuild = buildEngines['yotta']

export function setThisBuild(b: BuildEngine) {
thisBuild = b;
}

function patchYottaHexInfo(extInfo: pxtc.ExtensionInfo) {
let buildEngine = buildEngines['yotta']
let hexPath = buildEngine.buildPath + "/build/" + pxt.appTarget.compileService.yottaTarget
Expand Down Expand Up @@ -486,7 +489,7 @@ export function buildDalConst(buildEngine: BuildEngine, mainPkg: pxt.MainPackage
}

const writeFileAsync: any = Promise.promisify(fs.writeFile)
const execAsync: (cmd: string, options?: { cwd?: string }) => Promise<Buffer> = Promise.promisify(child_process.exec)
const execAsync: (cmd: string, options?: { cwd?: string }) => Promise<Buffer | string> = Promise.promisify(child_process.exec)
const readDirAsync = Promise.promisify(fs.readdir)

function buildFinalCsAsync(res: ts.pxtc.CompileResult) {
Expand Down Expand Up @@ -529,7 +532,7 @@ function getBoardDrivesAsync(): Promise<string[]> {
if (process.platform == "win32") {
const rx = new RegExp("^([A-Z]:)\\s+(\\d+).* " + pxt.appTarget.compile.deployDrives)
return execAsync("wmic PATH Win32_LogicalDisk get DeviceID, VolumeName, FileSystem, DriveType")
.then(buf => {
.then((buf: Buffer) => {
let res: string[] = []
buf.toString("utf8").split(/\n/).forEach(ln => {
let m = rx.exec(ln)
Expand Down
50 changes: 24 additions & 26 deletions cli/cli.ts
@@ -1,4 +1,3 @@
/// <reference path="../typings/globals/node/index.d.ts"/>
/// <reference path="../built/pxtlib.d.ts"/>
/// <reference path="../built/pxtcompiler.d.ts"/>
/// <reference path="../built/pxtsim.d.ts"/>
Expand Down Expand Up @@ -856,7 +855,7 @@ function uploadToGitRepoAsync(opts: UploadOptions, uplReqs: Map<BlobReq>) {
for (let u of U.values(uplReqs)) {
let fpath = path.join(trgPath, u.filename)
nodeutil.mkdirP(path.dirname(fpath))
fs.writeFileSync(fpath, u.content, u.encoding)
fs.writeFileSync(fpath, u.content, { encoding: u.encoding })
}
// make sure there's always something to commit
fs.writeFileSync(trgPath + "/stamp.txt", new Date().toString())
Expand Down Expand Up @@ -998,7 +997,7 @@ function uploadCoreAsync(opts: UploadOptions) {
}
if (!rdf) {
if (!fs.existsSync(p))
return;
return undefined;
rdf = readFileAsync(p)
}

Expand Down Expand Up @@ -1399,7 +1398,7 @@ function buildFolderAndBrowserifyAsync(p: string, optional?: boolean, outputName
}
});

let outFile = fs.createWriteStream(`built/${outputName}.js`, 'utf8');
let outFile = fs.createWriteStream(`built/${outputName}.js`, { encoding: 'utf8' });
b.bundle().pipe(outFile);

return new Promise<void>((resolve, reject) => {
Expand Down Expand Up @@ -1618,11 +1617,11 @@ function buildSemanticUIAsync(parsed?: commandParser.ParsedCommand) {
fs.readFile(`built/web/${cssFile}`, "utf8", (err, css) => {
postcss([cssnano])
.process(css, { from: `built/web/${cssFile}`, to: `built/web/${cssFile}` }).then((result: any) => {
fs.writeFile(`built/web/${cssFile}`, result.css, (err2, css2) => {
fs.writeFile(`built/web/${cssFile}`, result.css, (err2) => {
// process rtl css
postcss([rtlcss])
.process(result.css, { from: `built/web/${cssFile}`, to: `built/web/rtl${cssFile}` }).then((result2: any) => {
fs.writeFile(`built/web/rtl${cssFile}`, result2.css);
fs.writeFile(`built/web/rtl${cssFile}`, result2.css, undefined);
});
});
});
Expand Down Expand Up @@ -1690,7 +1689,7 @@ ${license}
tpn += `
------------- End of ThirdPartyNotices --------------------------------------------------- */`;

fs.writeFileSync("THIRD-PARTY-NOTICES.txt", tpn, 'utf8');
fs.writeFileSync("THIRD-PARTY-NOTICES.txt", tpn, { encoding: 'utf8' });
pxt.log('written THIRD-PARTY-NOTICES.txt');
return Promise.resolve();
}
Expand Down Expand Up @@ -2087,7 +2086,6 @@ export function serveAsync(parsed: commandParser.ParsedCommand) {

const readFileAsync: any = Promise.promisify(fs.readFile)
const writeFileAsync: any = Promise.promisify(fs.writeFile)
const execAsync: (cmd: string, options?: { cwd?: string }) => Promise<Buffer> = Promise.promisify(child_process.exec)
const readDirAsync = Promise.promisify(fs.readdir)
const statAsync = Promise.promisify(fs.stat)
const rimrafAsync = Promise.promisify(rimraf);
Expand Down Expand Up @@ -2307,14 +2305,14 @@ class Host
check(p)

if (U.endsWith(filename, ".uf2"))
fs.writeFileSync(p, contents, "base64")
fs.writeFileSync(p, contents, { encoding: "base64" })
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Node.js doesn't seem to deprecate string as encoding usage. Is the @types missing it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, you're right. Not sure why it was removed from the @types

else if (U.endsWith(filename, ".elf"))
fs.writeFileSync(p, contents, {
encoding: "base64",
mode: 0o777
})
else
fs.writeFileSync(p, contents, "utf8")
fs.writeFileSync(p, contents, { encoding: "utf8" })
}

getHexInfoAsync(extInfo: pxtc.ExtensionInfo): Promise<any> {
Expand Down Expand Up @@ -2466,7 +2464,7 @@ pxt_modules
"files.associations": {
"*.blocks": "html",
"*.jres": "json"
},
},
"search.exclude": {
"**/built": true,
"**/node_modules": true,
Expand Down Expand Up @@ -2790,7 +2788,7 @@ export function formatAsync(parsed: commandParser.ParsedCommand) {
if (expected == null)
expected = input
if (formatted != expected) {
fs.writeFileSync(fn, formatted, "utf8")
fs.writeFileSync(fn, formatted, { encoding: "utf8" })
console.log("format test FAILED; written:", fn)
numErr++;
} else {
Expand All @@ -2802,10 +2800,10 @@ export function formatAsync(parsed: commandParser.ParsedCommand) {
if (!inPlace)
fs.unlink(fn, err => { })
} else if (inPlace) {
fs.writeFileSync(f, formatted, "utf8")
fs.writeFileSync(f, formatted, { encoding: "utf8" })
console.log("replaced:", f)
} else {
fs.writeFileSync(fn, formatted, "utf8")
fs.writeFileSync(fn, formatted, { encoding: "utf8" })
console.log("written:", fn)
}

Expand Down Expand Up @@ -2978,7 +2976,7 @@ function simshimAsync() {
pxt.debug("no sim folder, skipping.")
return Promise.resolve();
}
let prog = pxtc.plainTsc("sim")
let prog = pxtc.plainTsc(path.resolve("sim"))
let shims = pxt.simshim(prog)
let filename = "sims.d.ts"
for (const s of Object.keys(shims)) {
Expand Down Expand Up @@ -3761,7 +3759,7 @@ export function downloadTargetTranslationsAsync(parsed: commandParser.ParsedComm
const tf = path.join(tfdir, fn);
nodeutil.mkdirP(tfdir)
pxt.log(`writing ${tf}`);
fs.writeFile(tf, langTranslations, "utf8");
fs.writeFile(tf, langTranslations, { encoding: "utf8" }, undefined);

locFiles[path.relative(projectdir, tf).replace(/\\/g, '/')] = "1";
})
Expand All @@ -3775,7 +3773,7 @@ export function downloadTargetTranslationsAsync(parsed: commandParser.ParsedComm
let local: pxt.PackageConfig = nodeutil.readJson(pxtJsonf)
local.files = pxtJson.files
pxt.log(`writing ${pxtJsonf}`);
fs.writeFileSync(pxtJsonf, JSON.stringify(local, null, 4), "utf8");
fs.writeFileSync(pxtJsonf, JSON.stringify(local, null, 4), { encoding: "utf8" });
}
return nextFileAsync()
});
Expand All @@ -3802,7 +3800,7 @@ export function staticpkgAsync(parsed: commandParser.ParsedCommand) {

pxt.log(`packaging editor to ${builtPackaged}`)

let p = rimrafAsync(builtPackaged, {})
let p = rimrafAsync(builtPackaged, {}, null)
.then(() => bump ? bumpAsync() : Promise.resolve())
.then(() => internalBuildTargetAsync({ packaged: true }));
if (ghpages) return p.then(() => ghpPushAsync(builtPackaged, minify));
Expand All @@ -3827,9 +3825,9 @@ function internalStaticPkgAsync(builtPackaged: string, label: string, minify: bo

export function cleanAsync(parsed: commandParser.ParsedCommand) {
pxt.log('cleaning built folders')
return rimrafAsync("built", {})
.then(() => rimrafAsync("libs/**/built", {}))
.then(() => rimrafAsync("projects/**/built", {}))
return rimrafAsync("built", {}, null)
.then(() => rimrafAsync("libs/**/built", {}, null))
.then(() => rimrafAsync("projects/**/built", {}, null))
.then(() => { });
}

Expand Down Expand Up @@ -3981,7 +3979,7 @@ function fetchTextAsync(filename: string): Promise<Buffer> {
if (/\.json$/i.test(filename)) pxt.log(`compile log: ${filename.replace(/\.json$/i, ".log")}`)
return U.requestAsync({ url: filename, allowHttpErrors: !!fn2 })
.then(resp => {
if (fn2 && (resp.statusCode != 200 || /html/.test(resp.headers["content-type"]))) {
if (fn2 && (resp.statusCode != 200 || /html/.test(resp.headers["content-type"] as string))) {
pxt.log(`Trying also ${fn2}...`)
return U.requestAsync({ url: fn2 })
} return resp
Expand Down Expand Up @@ -4064,7 +4062,7 @@ function extractBufferAsync(buf: Buffer, outDir: string): Promise<string[]> {
.then(json => {
if (!json) {
console.log("Couldn't extract.")
return
return undefined;
}
if (Array.isArray(json.scripts)) {
console.log("Legacy TD workspace.")
Expand All @@ -4090,7 +4088,7 @@ function extractBufferAsync(buf: Buffer, outDir: string): Promise<string[]> {
let prjs: SavedProject[] = json.projects
if (!prjs) {
console.log("No projects found.")
return
return undefined;
}
const dirs = writeProjects(prjs, outDir)
return dirs;
Expand Down Expand Up @@ -4319,7 +4317,7 @@ function internalCheckDocsAsync(compileSnippets?: boolean, re?: string): Promise
}

pxt.log(`checked ${checked} files: ${broken} broken links, ${noTOCs.length} not in SUMMARY, ${snippets.length} snippets`);
fs.writeFileSync("built/noSUMMARY.md", noTOCs.sort().map(p => `${Array(p.split(/[\/\\]/g).length - 1).join(' ')}* [${pxt.Util.capitalize(p.split(/[\/\\]/g).reverse()[0].split('-').join(' '))}](${p})`).join('\n'), "utf8");
fs.writeFileSync("built/noSUMMARY.md", noTOCs.sort().map(p => `${Array(p.split(/[\/\\]/g).length - 1).join(' ')}* [${pxt.Util.capitalize(p.split(/[\/\\]/g).reverse()[0].split('-').join(' '))}](${p})`).join('\n'), { encoding: "utf8" });

let p = Promise.resolve();
if (compileSnippets)
Expand Down Expand Up @@ -4989,7 +4987,7 @@ export function mainCli(targetDir: string, args: string[] = process.argv.slice(2
pxt.HF2.enableLog()

if (compileId != "none") {
build.thisBuild = build.buildEngines[compileId]
build.setThisBuild(build.buildEngines[compileId]);
if (!build.thisBuild) U.userError("cannot find build engine: " + compileId)
}

Expand Down
2 changes: 0 additions & 2 deletions cli/electron.ts
@@ -1,5 +1,3 @@
/// <reference path="../typings/modules/request/index.d.ts"/>

"use strict";

import * as p from "./commandparser";
Expand Down
2 changes: 0 additions & 2 deletions cli/gdb.ts
@@ -1,5 +1,3 @@
/// <reference path="../typings/globals/node/index.d.ts"/>

import * as path from 'path';
import * as nodeutil from './nodeutil';
import * as child_process from 'child_process';
Expand Down
10 changes: 4 additions & 6 deletions cli/nodeutil.ts
Expand Up @@ -176,8 +176,6 @@ function nodeHttpRequestAsync(options: Util.HttpRequestOptions): Promise<Util.Ht
let data = options.data
u.method = options.method || (data == null ? "GET" : "POST");

let mod = isHttps ? https : http;

let buf: Buffer = null;

u.headers["accept-encoding"] = "gzip"
Expand Down Expand Up @@ -209,7 +207,7 @@ function nodeHttpRequestAsync(options: Util.HttpRequestOptions): Promise<Util.Ht
u.headers['content-length'] = buf.length

return new Promise<Util.HttpResponse>((resolve, reject) => {
let req = mod.request(u, res => {
const handleResponse = (res: http.IncomingMessage) => {
let g: events.EventEmitter = res;
if (/gzip/.test(res.headers['content-encoding'])) {
let tmp = zlib.createUnzip();
Expand All @@ -231,7 +229,9 @@ function nodeHttpRequestAsync(options: Util.HttpRequestOptions): Promise<Util.Ht
}
return resp;
}))
})
};

const req = isHttps ? https.request(u, handleResponse) : http.request(u, handleResponse);
req.on('error', (err: any) => reject(err))
req.end(buf)
})
Expand Down Expand Up @@ -397,7 +397,6 @@ function getBrowserLocation(browser: string) {
if (normalizedBrowser === "chrome") {
switch (os.platform()) {
case "win32":
case "win64":
browserPath = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe";
break;
case "darwin":
Expand All @@ -414,7 +413,6 @@ function getBrowserLocation(browser: string) {
browserPath = "C:/Program Files (x86)/Mozilla Firefox/firefox.exe";
switch (os.platform()) {
case "win32":
case "win64":
browserPath = "C:/Program Files (x86)/Mozilla Firefox/firefox.exe";
break;
case "darwin":
Expand Down
4 changes: 1 addition & 3 deletions cli/serial.ts
@@ -1,5 +1,3 @@
/// <reference path="../typings/globals/node/index.d.ts"/>

import * as fs from 'fs';
import * as path from 'path';
import * as url from 'url';
Expand Down Expand Up @@ -275,7 +273,7 @@ export function flashSerialAsync(c: commandParser.ParsedCommand) {
/*
#define wait_ready() \
while (NVMCTRL->INTFLAG.bit.READY == 0);

void flash_write(void) {
uint32_t *src = (void *)0x20006000;
uint32_t *dst = (void *)*src++;
Expand Down
4 changes: 1 addition & 3 deletions cli/server.ts
@@ -1,5 +1,3 @@
/// <reference path="../typings/globals/node/index.d.ts"/>

import * as fs from 'fs';
import * as path from 'path';
import * as http from 'http';
Expand Down Expand Up @@ -253,7 +251,7 @@ function getCachedHexAsync(sha: string): Promise<any> {
}

function handleApiAsync(req: http.IncomingMessage, res: http.ServerResponse, elts: string[]): Promise<any> {
const opts: pxt.Map<string> = querystring.parse(url.parse(req.url).query)
const opts: pxt.Map<string | string[]> = querystring.parse(url.parse(req.url).query)
const innerPath = elts.slice(2).join("/").replace(/^\//, "")
const filename = path.resolve(path.join(userProjectsDir, innerPath))
const meth = req.method.toUpperCase()
Expand Down
3 changes: 2 additions & 1 deletion libs/pxt-common/pxt-core.d.ts
Expand Up @@ -225,6 +225,7 @@ interface Object { }
interface Function { }
interface IArguments { }
interface RegExp { }
type TemplateStringsArray = Array<string>;

type uint8 = number;
type uint16 = number;
Expand Down Expand Up @@ -293,7 +294,7 @@ declare namespace Math {
function random(): number;

/**
* Returns a pseudorandom number between min and max included.
* Returns a pseudorandom number between min and max included.
* If both numbers are integral, the result is integral.
* @param min the lower inclusive bound, eg: 0
* @param max the upper inclusive bound, eg: 10
Expand Down