doric-cli:use ws instead

This commit is contained in:
pengfeizhou 2021-02-19 17:57:15 +08:00 committed by osborn
parent 60b61f66ca
commit d40cd13c56
4 changed files with 87 additions and 87 deletions

View File

@ -4,7 +4,7 @@
{ {
"type": "node", "type": "node",
"request": "launch", "request": "launch",
"name": "Debug TS", "name": "Doric Debugger",
"program": "${workspaceFolder}/${relativeFile}", "program": "${workspaceFolder}/${relativeFile}",
"preLaunchTask": "Doric Build", "preLaunchTask": "Doric Build",
"sourceMaps": true, "sourceMaps": true,

View File

@ -32,14 +32,17 @@
"commander": "^6.0.0", "commander": "^6.0.0",
"glob": "^7.1.6", "glob": "^7.1.6",
"keypress": "^0.2.1", "keypress": "^0.2.1",
"nodejs-websocket": "^1.7.2",
"qrcode-terminal": "^0.12.0", "qrcode-terminal": "^0.12.0",
"rollup": "^2.23.0", "rollup": "^2.23.0",
"shelljs": "^0.8.4", "shelljs": "^0.8.4",
"source-map-merger": "^0.2.0", "source-map-merger": "^0.2.0",
"typescript": "^3.9.7" "typescript": "^3.9.7",
"ws": "^7.4.3"
}, },
"publishConfig": { "publishConfig": {
"registry": "https://registry.npmjs.org" "registry": "https://registry.npmjs.org"
},
"devDependencies": {
"@types/ws": "^7.4.0"
} }
} }

View File

@ -59,7 +59,6 @@ export default async function dev() {
process.stdin.resume(); process.stdin.resume();
await delay(3000); await delay(3000);
console.warn("Start watching"); console.warn("Start watching");
server.listen(7777);
const cachedContents: Record<string, string> = {} const cachedContents: Record<string, string> = {}
chokidar chokidar
.watch(process.cwd() + "/bundle", { .watch(process.cwd() + "/bundle", {
@ -87,8 +86,8 @@ export default async function dev() {
if (fs.existsSync(sourceMap)) { if (fs.existsSync(sourceMap)) {
mergeMap(sourceMap); mergeMap(sourceMap);
} }
server.connections.forEach((e: any) => { server.clients.forEach((e) => {
e.sendText( e.send(
JSON.stringify({ JSON.stringify({
cmd: "RELOAD", cmd: "RELOAD",
script: content, script: content,

View File

@ -1,95 +1,93 @@
import fs from "fs"; import fs from "fs";
import { exec, spawn } from "child_process"; import WebSocket from "ws"
import ws from "nodejs-websocket";
import "colors"; import "colors";
import path from "path"; import path from "path";
import { delay, glob } from "./util"; import { delay, glob } from "./util";
import { Shell } from "./shell"; import { Shell } from "./shell";
export async function createServer() { export async function createServer() {
console.log("Create Server")
let contextId: string = "0" let contextId: string = "0"
let clientConnection: any = null let clientConnection: WebSocket | undefined = undefined
let debuggerConnection: any = null let debuggerConnection: WebSocket | undefined = undefined
let deviceId = 0 let deviceId = 0
const server = (ws as any).createServer((connection: any) => { return new WebSocket.Server({ port: 7777 })
let thisDeviceId = deviceId++ .on("connection", (ws, request) => {
console.log('Connected', connection.headers.host) let thisDeviceId = `Client#${deviceId++}`
if (connection.headers.host.startsWith("localhost")) { console.log('Connected', request.headers.host)
console.log(`Debugger ${thisDeviceId} attached to dev kit`.green) if (request.headers.host?.startsWith("localhost")) {
debuggerConnection = connection console.log(`Debugger ${thisDeviceId} attached to dev kit`.green)
clientConnection.sendText(JSON.stringify({ debuggerConnection = ws
cmd: 'SWITCH_TO_DEBUG', clientConnection?.send(JSON.stringify({
contextId: contextId cmd: 'SWITCH_TO_DEBUG',
}), () => { }) contextId: contextId
} else { }))
console.log(`Client ${thisDeviceId} attached to dev kit`.green) } else {
} console.log(`${thisDeviceId} attached to dev kit`.green)
connection.on('text', async function (result: string) {
let resultObject = JSON.parse(result)
switch (resultObject.cmd) {
case 'DEBUG':
clientConnection = connection;
(server as any).debugging = true;
console.log("Enter debugging");
contextId = resultObject.data.contextId;
const projectHome = '.';
await fs.promises.writeFile(path.resolve(projectHome, "build", "context"), contextId, "utf-8");
let source = resultObject.data.source as string;
if (source.startsWith(".js")) {
source = source.replace(".js", ".ts");
} else if (!source.startsWith(".ts")) {
source = source + ".ts"
}
let sourceFile = path.resolve(projectHome, "src", source);
if (!fs.existsSync(sourceFile)) {
const tsFiles = await glob(source, {
cwd: path.resolve(projectHome, "src")
})
if (!!!tsFiles || tsFiles.length === 0) {
console.error(`Cannot find ${source} in ${path.resolve(projectHome)}`);
}
sourceFile = tsFiles[0];
}
console.log(connection.key + " request debug, project home: " + projectHome);
await Shell.exec("code", [projectHome, sourceFile]);
await delay(1500);
break;
case 'EXCEPTION':
console.log(resultObject.data.source.red);
console.log(resultObject.data.exception.red);
break;
case 'LOG':
const date = new Date
const format = function (num: number) {
return (Array(2).join("0") + num).slice(-2);
};
const timeStr = `${format(date.getHours())}:${format(date.getMinutes())}:${format(date.getSeconds())}.${(Array(3).join("0") + date.getMilliseconds()).slice(-3)}`
let logContent = resultObject.data.message as string
if (resultObject.data.type == 'DEFAULT') {
console.log(`${timeStr} Device ${thisDeviceId} ${"[I]".green} ${logContent.green}`.bgBlue);
} else if (resultObject.data.type == 'ERROR') {
console.log(`${timeStr} Device ${thisDeviceId} ${"[E]".green} ${logContent.green}`.bgRed);
} else if (resultObject.data.type == 'WARN') {
console.log(`${timeStr.black} ${("Device " + thisDeviceId).black} ${"[W]".green} ${logContent.green}`.bgYellow);
}
break
} }
ws.on('text', async function (result: string) {
let resultObject = JSON.parse(result)
switch (resultObject.cmd) {
case 'DEBUG':
clientConnection = ws;
(ws as any).debugging = true;
console.log("Enter debugging");
contextId = resultObject.data.contextId;
const projectHome = '.';
await fs.promises.writeFile(path.resolve(projectHome, "build", "context"), contextId, "utf-8");
let source = resultObject.data.source as string;
if (source.startsWith(".js")) {
source = source.replace(".js", ".ts");
} else if (!source.startsWith(".ts")) {
source = source + ".ts"
}
let sourceFile = path.resolve(projectHome, "src", source);
if (!fs.existsSync(sourceFile)) {
const tsFiles = await glob(source, {
cwd: path.resolve(projectHome, "src")
})
if (!!!tsFiles || tsFiles.length === 0) {
console.error(`Cannot find ${source} in ${path.resolve(projectHome)}`);
}
sourceFile = tsFiles[0];
}
console.log(thisDeviceId + " request debug, project home: " + projectHome);
await Shell.exec("code", [projectHome, sourceFile]);
await delay(1500);
break;
case 'EXCEPTION':
console.log(resultObject.data.source.red);
console.log(resultObject.data.exception.red);
break;
case 'LOG':
const date = new Date
const format = function (num: number) {
return (Array(2).join("0") + num).slice(-2);
};
const timeStr = `${format(date.getHours())}:${format(date.getMinutes())}:${format(date.getSeconds())}.${(Array(3).join("0") + date.getMilliseconds()).slice(-3)}`
let logContent = resultObject.data.message as string
if (resultObject.data.type == 'DEFAULT') {
console.log(`${timeStr} ${thisDeviceId} ${"[I]".green} ${logContent.green}`.bgBlue);
} else if (resultObject.data.type == 'ERROR') {
console.log(`${timeStr} ${thisDeviceId} ${"[E]".green} ${logContent.green}`.bgRed);
} else if (resultObject.data.type == 'WARN') {
console.log(`${timeStr.black} ${thisDeviceId.black} ${"[W]".green} ${logContent.green}`.bgYellow);
}
break
}
})
ws.on('connect', function (code: number) {
console.log('connect', code)
})
ws.on('close', function (code: number) {
console.log('close: code = ' + code, thisDeviceId)
console.log("quit debugging");
(ws as any).debugging = false
})
ws.on('error', function (code: number) {
console.log('error', code)
})
}) })
connection.on('connect', function (code: number) {
console.log('connect', code)
})
connection.on('close', function (code: number) {
console.log('close: code = ' + code, connection.key)
console.log("quit debugging");
(server as any).debugging = false
})
connection.on('error', function (code: number) {
console.log('error', code)
})
})
return server
} }