Refact:Devkit change msg format

This commit is contained in:
pengfeizhou 2021-02-20 17:58:09 +08:00 committed by osborn
parent d40cd13c56
commit 4c0237aec6
21 changed files with 459 additions and 319 deletions

View File

@ -31,7 +31,6 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation "com.google.android.material:material:1.1.0"
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
implementation 'com.google.code.gson:gson:2.8.5'
api 'org.greenrobot:eventbus:3.2.0'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'

View File

@ -2,13 +2,10 @@ package pub.doric.devkit;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;
import pub.doric.Doric;
import pub.doric.DoricContext;
@ -16,17 +13,14 @@ import pub.doric.DoricContextManager;
import pub.doric.DoricNativeDriver;
import pub.doric.devkit.event.ConnectExceptionEvent;
import pub.doric.devkit.event.EOFExceptionEvent;
import pub.doric.devkit.event.EnterDebugEvent;
import pub.doric.devkit.event.OpenEvent;
import pub.doric.devkit.event.ReloadEvent;
import pub.doric.devkit.event.StartDebugEvent;
import pub.doric.devkit.event.StopDebugEvent;
public class DevKit implements IDevKit {
public static boolean isRunningInEmulator = false;
public static String ip = "";
private static Gson gson = new Gson();
private static class Inner {
private static final DevKit sInstance = new DevKit();
@ -50,11 +44,8 @@ public class DevKit implements IDevKit {
}
@Override
public void sendDevCommand(IDevKit.Command command, JsonObject jsonObject) {
JsonObject result = new JsonObject();
result.addProperty("cmd", command.toString());
result.add("data", jsonObject);
wsClient.send(gson.toJson(result));
public void sendDevCommand(IDevKit.Command command, JSONObject jsonObject) {
wsClient.sendToServer(command.toString(), jsonObject);
}
@Override
@ -85,31 +76,29 @@ public class DevKit implements IDevKit {
Toast.makeText(Doric.application(), "dev kit connection exception", Toast.LENGTH_LONG).show();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onStartDebugEvent(StartDebugEvent startDebugEvent) {
doricContextDebuggable = new DoricContextDebuggable(startDebugEvent.getContextId());
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEnterDebugEvent(EnterDebugEvent enterDebugEvent) {
doricContextDebuggable.startDebug();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onQuitDebugEvent(StopDebugEvent quitDebugEvent) {
doricContextDebuggable.stopDebug();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onReloadEvent(ReloadEvent reloadEvent) {
public DoricContext requestDebugContext(String source) {
for (DoricContext context : DoricContextManager.aliveContexts()) {
if (source.contains(context.getSource()) || context.getSource().equals("__dev__")) {
return context;
}
}
return null;
}
public void reload(String source, String script) {
for (DoricContext context : DoricContextManager.aliveContexts()) {
if (doricContextDebuggable != null &&
doricContextDebuggable.isDebugging &&
doricContextDebuggable.getContext().getContextId().equals(context.getContextId())) {
System.out.println("is debugging context id: " + context.getContextId());
} else {
if (reloadEvent.source.contains(context.getSource()) || context.getSource().equals("__dev__")) {
context.reload(reloadEvent.script);
if (source.contains(context.getSource()) || context.getSource().equals("__dev__")) {
context.reload(script);
}
}
}

View File

@ -1,43 +1,35 @@
package pub.doric.devkit;
import pub.doric.DoricContext;
import pub.doric.DoricContextManager;
import pub.doric.DoricNativeDriver;
import pub.doric.utils.DoricConstant;
import pub.doric.IDoricDriver;
public class DoricContextDebuggable {
private DoricContext doricContext;
private DoricDebugDriver doricDebugDriver;
private final DoricContext doricContext;
private DoricDebugDriver debugDriver;
private final IDoricDriver nativeDriver;
public boolean isDebugging = false;
public DoricContextDebuggable(String contextId) {
this.doricContext = DoricContextManager.getContext(contextId);
isDebugging = true;
public DoricContextDebuggable(DoricContext doricContext) {
this.doricContext = doricContext;
this.isDebugging = true;
this.nativeDriver = this.doricContext.getDriver();
}
public void startDebug() {
doricDebugDriver = new DoricDebugDriver(new IStatusCallback() {
debugDriver = new DoricDebugDriver(new IStatusCallback() {
@Override
public void start() {
doricContext.setDriver(doricDebugDriver);
doricContext.getRootNode().setId("");
doricContext.callEntity(DoricConstant.DORIC_ENTITY_INIT, doricContext.getExtra());
doricContext.callEntity(DoricConstant.DORIC_ENTITY_CREATE);
doricContext.callEntity(DoricConstant.DORIC_ENTITY_BUILD, doricContext.getInitParams());
doricContext.setDriver(debugDriver);
doricContext.reload(doricContext.getScript());
}
});
}
public void stopDebug() {
isDebugging = false;
doricDebugDriver.destroy();
doricContext.setDriver(DoricNativeDriver.getInstance());
doricContext.getRootNode().setId("");
doricContext.callEntity(DoricConstant.DORIC_ENTITY_INIT, doricContext.getExtra());
doricContext.callEntity(DoricConstant.DORIC_ENTITY_CREATE);
doricContext.callEntity(DoricConstant.DORIC_ENTITY_BUILD, doricContext.getInitParams());
doricContext.setDriver(nativeDriver);
debugDriver.destroy();
doricContext.reload(doricContext.getScript());
}
public DoricContext getContext() {

View File

@ -1,18 +1,7 @@
package pub.doric.devkit;
import android.util.Log;
import androidx.annotation.Nullable;
import com.google.gson.JsonObject;
import java.io.PrintWriter;
import java.io.StringWriter;
import pub.doric.DoricContext;
import pub.doric.devkit.remote.DoricRemoteJSExecutor;
import pub.doric.engine.DoricJSEngine;
import pub.doric.utils.DoricLog;
public class DoricDebugJSEngine extends DoricJSEngine {
@ -27,41 +16,4 @@ public class DoricDebugJSEngine extends DoricJSEngine {
protected void initJSEngine() {
mDoricJSE = new DoricRemoteJSExecutor(statusCallback);
}
@Override
public void onException(@Nullable DoricContext context, Exception e) {
Log.e(DoricJSEngine.class.getSimpleName(), "In source file: " + (context != null ? context.getSource() : "Unknown"));
e.printStackTrace();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("source", "In source file: " + (context != null ? context.getSource() : "Unknown"));
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
jsonObject.addProperty("exception", stringWriter.toString());
DevKit.getInstance().sendDevCommand(IDevKit.Command.EXCEPTION, jsonObject);
}
@Override
public void onLog(int type, String message) {
String typeString = "DEFAULT";
switch (type) {
case Log.ERROR:
DoricLog.suffix_e("_js", message);
typeString = "ERROR";
break;
case Log.WARN:
DoricLog.suffix_w("_js", message);
typeString = "WARN";
break;
default:
DoricLog.suffix_d("_js", message);
break;
}
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", typeString);
jsonObject.addProperty("message", message);
DevKit.getInstance().sendDevCommand(IDevKit.Command.LOG, jsonObject);
}
}

View File

@ -17,7 +17,7 @@ package pub.doric.devkit;
import android.util.Log;
import com.google.gson.JsonObject;
import com.github.pengfeizhou.jscore.JSONBuilder;
import java.io.PrintWriter;
import java.io.StringWriter;
@ -37,12 +37,14 @@ public class DoricDevMonitor implements IDoricMonitor {
if (!DoricDev.getInstance().isInDevMode()) {
return;
}
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("source", "In source file: " + (context != null ? context.getSource() : "Unknown"));
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
jsonObject.addProperty("exception", stringWriter.toString());
DevKit.getInstance().sendDevCommand(IDevKit.Command.EXCEPTION, jsonObject);
DevKit.getInstance().sendDevCommand(
IDevKit.Command.EXCEPTION,
new JSONBuilder()
.put("source", "In source file: " + (context != null ? context.getSource() : "Unknown"))
.put("exception", stringWriter.toString())
.toJSONObject());
}
@Override
@ -64,9 +66,11 @@ public class DoricDevMonitor implements IDoricMonitor {
DoricLog.suffix_d("_js", message);
break;
}
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", typeString);
jsonObject.addProperty("message", message);
DevKit.getInstance().sendDevCommand(IDevKit.Command.LOG, jsonObject);
DevKit.getInstance().sendDevCommand(
IDevKit.Command.LOG,
new JSONBuilder()
.put("type", typeString)
.put("message", message)
.toJSONObject());
}
}

View File

@ -1,16 +1,17 @@
package pub.doric.devkit;
import com.google.gson.JsonObject;
import org.json.JSONObject;
public interface IDevKit {
enum Command {
DEBUG, HOT_RELOAD, EXCEPTION, LOG
HOT_RELOAD, EXCEPTION, LOG
}
void connectDevKit(String url);
void sendDevCommand(IDevKit.Command command, JsonObject jsonObject);
void sendDevCommand(IDevKit.Command command, JSONObject jsonObject);
void disconnectDevKit();
}

View File

@ -15,6 +15,8 @@
*/
package pub.doric.devkit;
import com.github.pengfeizhou.jscore.JSONBuilder;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
@ -28,11 +30,10 @@ import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import pub.doric.DoricContext;
import pub.doric.devkit.event.ConnectExceptionEvent;
import pub.doric.devkit.event.EOFExceptionEvent;
import pub.doric.devkit.event.EnterDebugEvent;
import pub.doric.devkit.event.OpenEvent;
import pub.doric.devkit.event.ReloadEvent;
/**
* @Description: com.github.penfeizhou.doric.dev
@ -68,19 +69,24 @@ public class WSClient extends WebSocketListener {
super.onMessage(webSocket, text);
try {
JSONObject jsonObject = new JSONObject(text);
String type = jsonObject.optString("type");
String cmd = jsonObject.optString("cmd");
switch (cmd) {
case "RELOAD": {
String source = jsonObject.optString("source");
String script = jsonObject.optString("script");
EventBus.getDefault().post(new ReloadEvent(source, script));
JSONObject payload = jsonObject.optJSONObject("payload");
if ("D2C".equals(type)) {
if ("DEBUG_REQ".equals(cmd)) {
String source = payload.optString("source");
DoricContext context = DevKit.getInstance().requestDebugContext(source);
sendToDebugger("DEBUG_RES", new JSONBuilder()
.put("contextId", context == null ? "" : context.getContextId())
.toJSONObject());
}
break;
case "SWITCH_TO_DEBUG": {
String contextId = jsonObject.optString("contextId");
EventBus.getDefault().post(new EnterDebugEvent());
} else if ("S2C".equals(type)) {
if ("RELOAD".equals(cmd)) {
String source = payload.optString("source");
String script = payload.optString("script");
DevKit.getInstance().reload(source, script);
}
break;
}
} catch (JSONException e) {
@ -111,7 +117,20 @@ public class WSClient extends WebSocketListener {
}
}
public void send(String command) {
webSocket.send(command);
public void sendToDebugger(String command, JSONObject payload) {
webSocket.send(new JSONBuilder()
.put("type", "C2D")
.put("cmd", command)
.put("payload", payload)
.toString());
}
public void sendToServer(String command, JSONObject payload) {
webSocket.send(new JSONBuilder()
.put("type", "C2S")
.put("cmd", command)
.put("payload", payload)
.toString());
}
}

View File

@ -1,5 +0,0 @@
package pub.doric.devkit.event;
public class EnterDebugEvent {
}

View File

@ -1,4 +0,0 @@
package pub.doric.devkit.event;
public class QuitDebugEvent {
}

View File

@ -1,11 +0,0 @@
package pub.doric.devkit.event;
public class ReloadEvent {
public String source;
public String script;
public ReloadEvent(String source, String script) {
this.source = source;
this.script = script;
}
}

View File

@ -1,13 +0,0 @@
package pub.doric.devkit.event;
public class StartDebugEvent {
private String contextId;
public StartDebugEvent(String contextId) {
this.contextId = contextId;
}
public String getContextId() {
return contextId;
}
}

View File

@ -17,8 +17,6 @@ import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.gson.JsonObject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
@ -27,12 +25,10 @@ import pub.doric.DoricContext;
import pub.doric.DoricContextManager;
import pub.doric.devkit.DevKit;
import pub.doric.devkit.DoricDev;
import pub.doric.devkit.IDevKit;
import pub.doric.devkit.R;
import pub.doric.devkit.event.ConnectExceptionEvent;
import pub.doric.devkit.event.EOFExceptionEvent;
import pub.doric.devkit.event.OpenEvent;
import pub.doric.devkit.event.StartDebugEvent;
import pub.doric.devkit.qrcode.DisplayUtil;
import pub.doric.devkit.qrcode.activity.CaptureActivity;
import pub.doric.devkit.qrcode.activity.CodeUtils;
@ -154,11 +150,7 @@ public class DoricDevActivity extends AppCompatActivity {
cell.findViewById(R.id.debug_text_view).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post(new StartDebugEvent(doricContext.getContextId()));
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("contextId", doricContext.getContextId());
jsonObject.addProperty("source", doricContext.getSource().replace(".js", ".ts"));
DevKit.getInstance().sendDevCommand(IDevKit.Command.DEBUG, jsonObject);
}
});

View File

@ -1,6 +1,6 @@
import { exec } from "child_process"
import chokidar from "chokidar";
import { createServer } from "./server"
import { createServer, MSG } from "./server"
import { delay } from "./util";
import fs from "fs";
import { mergeMap } from "./actions";
@ -89,11 +89,14 @@ export default async function dev() {
server.clients.forEach((e) => {
e.send(
JSON.stringify({
type: "S2C",
cmd: "RELOAD",
payload: {
script: content,
source: (jsFile.match(/[^/\\]*$/) || [""])[0],
sourceMap,
})
}
} as MSG)
);
});
} catch (e) {

View File

@ -5,6 +5,13 @@ import path from "path";
import { delay, glob } from "./util";
import { Shell } from "./shell";
export type MSG = {
type: "D2C" | "C2D" | "C2S" | "D2S" | "S2C" | "S2D",
cmd: string,
payload: { [index: string]: string }
}
export async function createServer() {
let contextId: string = "0"
let clientConnection: WebSocket | undefined = undefined
@ -12,9 +19,10 @@ export async function createServer() {
let deviceId = 0
return new WebSocket.Server({ port: 7777 })
.on("connection", (ws, request) => {
let thisDeviceId = `Client#${deviceId++}`
let thisDeviceId: string
console.log('Connected', request.headers.host)
if (request.headers.host?.startsWith("localhost")) {
thisDeviceId = `Debugger#${deviceId++}`
console.log(`Debugger ${thisDeviceId} attached to dev kit`.green)
debuggerConnection = ws
clientConnection?.send(JSON.stringify({
@ -22,19 +30,23 @@ export async function createServer() {
contextId: contextId
}))
} else {
thisDeviceId = `Client#${deviceId++}`
console.log(`${thisDeviceId} attached to dev kit`.green)
}
ws.on('text', async function (result: string) {
let resultObject = JSON.parse(result)
ws.on('message', async function (result: string) {
const resultObject = JSON.parse(result) as MSG
if (resultObject.type === "D2C" || resultObject.type === "C2D") {
ws.send(result);
} else if (resultObject.type === "C2S") {
switch (resultObject.cmd) {
case 'DEBUG':
clientConnection = ws;
(ws as any).debugging = true;
console.log("Enter debugging");
contextId = resultObject.data.contextId;
contextId = resultObject.payload.contextId;
const projectHome = '.';
await fs.promises.writeFile(path.resolve(projectHome, "build", "context"), contextId, "utf-8");
let source = resultObject.data.source as string;
let source = resultObject.payload.source as string;
if (source.startsWith(".js")) {
source = source.replace(".js", ".ts");
} else if (!source.startsWith(".ts")) {
@ -55,8 +67,8 @@ export async function createServer() {
await delay(1500);
break;
case 'EXCEPTION':
console.log(resultObject.data.source.red);
console.log(resultObject.data.exception.red);
console.log(resultObject.payload.source.red);
console.log(resultObject.payload.exception.red);
break;
case 'LOG':
const date = new Date
@ -64,17 +76,17 @@ export async function createServer() {
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') {
const logContent = resultObject.payload.message
if (resultObject.payload.type === 'DEFAULT') {
console.log(`${timeStr} ${thisDeviceId} ${"[I]".green} ${logContent.green}`.bgBlue);
} else if (resultObject.data.type == 'ERROR') {
} else if (resultObject.payload.type === 'ERROR') {
console.log(`${timeStr} ${thisDeviceId} ${"[E]".green} ${logContent.green}`.bgRed);
} else if (resultObject.data.type == 'WARN') {
} else if (resultObject.payload.type === 'WARN') {
console.log(`${timeStr.black} ${thisDeviceId.black} ${"[W]".green} ${logContent.green}`.bgYellow);
}
break
}
}
})
ws.on('connect', function (code: number) {
console.log('connect', code)

View File

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

View File

@ -1,23 +1,41 @@
import { text, vlayout, ViewHolder, VMPanel, ViewModel, Gravity, NativeCall, Text, Color, log, logw, loge, Group, LayoutSpec, layoutConfig, } from "doric"
import {
text,
vlayout,
ViewHolder,
VMPanel,
ViewModel,
Gravity,
NativeCall,
Text,
Color,
log,
logw,
loge,
Group,
LayoutSpec,
layoutConfig,
modal,
Panel,
} from "doric";
interface CountModel {
count: number
count: number;
}
class CounterView extends ViewHolder {
number!: Text
counter!: Text
number!: Text;
counter!: Text;
build(root: Group) {
vlayout(
[
text({
textSize: 40,
tag: "tvNumber"
tag: "tvNumber",
}),
text({
text: "Click To Count 1",
textSize: 20,
tag: "tvCounter"
tag: "tvCounter",
}),
],
{
@ -25,43 +43,45 @@ class CounterView extends ViewHolder {
gravity: Gravity.Center,
space: 20,
}
).in(root)
this.number = root.findViewByTag("tvNumber")!
this.counter = root.findViewByTag("tvCounter")!
).in(root);
this.number = root.findViewByTag("tvNumber")!;
this.counter = root.findViewByTag("tvCounter")!;
}
}
class CounterVM extends ViewModel<CountModel, CounterView> {
onAttached(s: CountModel, vh: CounterView) {
vh.counter.onClick = () => {
this.updateState(state => {
state.count++
})
}
this.updateState((state) => {
state.count++;
});
};
}
onBind(s: CountModel, vh: CounterView) {
vh.number.text = `${s.count}`
log("onBind\nseee")
logw("onBind")
loge("onBind")
vh.number.text = `${s.count}`;
log("onBind\nseee");
logw("onBind");
loge("onBind");
}
}
@Entry
export class CounterPage extends VMPanel<CountModel, CounterView> {
constructor() {
super();
log("Constructor");
}
getViewHolderClass() {
return CounterView
return CounterView;
}
getViewModelClass() {
return CounterVM
return CounterVM;
}
getState(): CountModel {
return {
count: 0
}
count: 1,
};
}
}

View File

@ -3,13 +3,11 @@
Object.defineProperty(exports, '__esModule', { value: true });
var WebSocket = require('ws');
var fs = require('fs');
var path = require('path');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var WebSocket__default = /*#__PURE__*/_interopDefaultLegacy(WebSocket);
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
/*
@ -4218,37 +4216,86 @@ class VMPanel extends Panel {
}
}
/*
* Copyright [2019] [Doric.Pub]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const contextFile = path__default['default'].resolve(process.cwd(), 'build', 'context');
const contextId = fs__default['default'].readFileSync(contextFile, { encoding: 'utf8' });
console.log("debugging context id: " + contextId);
var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
let contextId = undefined;
let global$2 = new Function('return this')();
global$2.setTimeout = global$2.doricSetTimeout;
global$2.setInterval = global$2.doricSetInterval;
global$2.clearTimeout = global$2.doricClearTimeout;
global$2.clearInterval = global$2.doricClearInterval;
global$2.doric = doric;
function initNativeEnvironment(source) {
return __awaiter$1(this, void 0, void 0, function* () {
// dev kit client
return new Promise((resolve, reject) => {
const devClient = new WebSocket__default['default']('ws://localhost:7777');
devClient.on('open', () => {
console.log('Connectted Devkit on port', '7777');
devClient.send(JSON.stringify({
type: "D2C",
payload: {
cmd: "DEBUG_REQ",
source,
},
}));
});
devClient.on('message', (data) => {
console.log(data);
const msg = JSON.parse(data);
switch (msg.cwd) {
case "DEBUG_RES":
const contextId = msg.contextId;
if ((contextId === null || contextId === void 0 ? void 0 : contextId.length) > 0) {
resolve(contextId);
}
else {
reject(`Cannot find applicable context in client for source ${source}`);
}
break;
}
});
devClient.on('error', (error) => {
console.log(error);
reject(error);
});
});
});
}
global$2.Entry = function () {
var _a, _b, _c;
if (!!contextId) {
return Reflect.apply(jsObtainEntry(contextId), doric, arguments);
}
else {
const jsFile = (_c = (_b = (_a = new Error().stack) === null || _a === void 0 ? void 0 : _a.split("\n").map(e => e.match(/at\s__decorate\s\((.*?)\)/)).find(e => !!e)) === null || _b === void 0 ? void 0 : _b[1].match(/(.*?\.js)/)) === null || _c === void 0 ? void 0 : _c[1];
if (!jsFile) {
throw new Error("Cannot find debugging file");
}
const source = path__default['default'].basename(jsFile);
const args = arguments;
console.log(`Debugging ${source}`);
initNativeEnvironment(source).then(ret => {
contextId = ret;
console.log("debugging context id: " + contextId);
global$2.context = jsObtainContext(contextId);
global$2.Entry = jsObtainEntry(contextId);
Reflect.apply(jsObtainEntry(contextId), doric, args);
}).catch(error => console.error(error));
return arguments[0];
}
};
// debug server
const debugServer = new WebSocket__default['default'].Server({ port: 2080 });
debugServer.on('connection', function connection(ws) {
debugServer.on('connection', (ws) => {
console.log('connected');
ws.on('message', function incoming(message) {
ws.on('message', (message) => {
let messageObject = JSON.parse(message);
switch (messageObject.cmd) {
case "injectGlobalJSObject":

View File

@ -15,27 +15,88 @@
*/
import * as doric from './src/runtime/sandbox'
import WebSocket from "ws"
import fs from "fs"
import path from 'path'
const contextFile = path.resolve(process.cwd(), 'build', 'context');
const contextId = fs.readFileSync(contextFile, { encoding: 'utf8' })
console.log("debugging context id: " + contextId)
type MSG = {
type: "D2C" | "C2D" | "C2S" | "D2S" | "S2C" | "S2D",
cmd: string,
payload: { [index: string]: string }
}
let contextId: string | undefined = undefined;
let global = new Function('return this')()
global.setTimeout = global.doricSetTimeout
global.setInterval = global.doricSetInterval
global.clearTimeout = global.doricClearTimeout
global.clearInterval = global.doricClearInterval
global.doric = doric
global.context = doric.jsObtainContext(contextId)
global.Entry = doric.jsObtainEntry(contextId)
async function initNativeEnvironment(source: string) {
// dev kit client
return new Promise<string>((resolve, reject) => {
const devClient = new WebSocket('ws://localhost:7777')
devClient.on('open', () => {
console.log('Connectted Devkit on port', '7777')
devClient.send(JSON.stringify({
type: "D2C",
payload: {
cmd: "DEBUG_REQ",
source,
},
}))
})
devClient.on('message', (data) => {
console.log(data)
const msg = JSON.parse(data as string) as { type: string, cwd: string, [idx: string]: string }
switch (msg.cwd) {
case "DEBUG_RES":
const contextId = msg.contextId;
if (contextId?.length > 0) {
resolve(contextId)
} else {
reject(`Cannot find applicable context in client for source ${source}`)
}
break;
}
})
devClient.on('error', (error) => {
console.log(error)
reject(error)
})
})
}
global.Entry = function () {
if (!!contextId) {
return Reflect.apply(doric.jsObtainEntry(contextId), doric, arguments);
} else {
const jsFile = new Error().stack?.split("\n")
.map(e => e.match(/at\s__decorate\s\((.*?)\)/))
.find(e => !!e)?.[1].match(/(.*?\.js)/)?.[1];
if (!jsFile) {
throw new Error("Cannot find debugging file");
}
const source = path.basename(jsFile)
const args = arguments
console.log(`Debugging ${source}`)
initNativeEnvironment(source).then(ret => {
contextId = ret;
console.log("debugging context id: " + contextId);
global.context = doric.jsObtainContext(contextId);
Reflect.apply(doric.jsObtainEntry(contextId), doric, args);
}).catch(error => console.error(error));
return arguments[0];
}
}
// debug server
const debugServer = new WebSocket.Server({ port: 2080 })
debugServer.on('connection', function connection(ws) {
debugServer.on('connection', (ws) => {
console.log('connected')
ws.on('message', function incoming(message: string) {
ws.on('message', (message: string) => {
let messageObject = JSON.parse(message)
switch (messageObject.cmd) {
case "injectGlobalJSObject":

View File

@ -1,3 +1,12 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
/*
* Copyright [2019] [Doric.Pub]
*
@ -15,24 +24,78 @@
*/
import * as doric from './src/runtime/sandbox';
import WebSocket from "ws";
import fs from "fs";
import path from 'path';
const contextFile = path.resolve(process.cwd(), 'build', 'context');
const contextId = fs.readFileSync(contextFile, { encoding: 'utf8' });
console.log("debugging context id: " + contextId);
let contextId = undefined;
let global = new Function('return this')();
global.setTimeout = global.doricSetTimeout;
global.setInterval = global.doricSetInterval;
global.clearTimeout = global.doricClearTimeout;
global.clearInterval = global.doricClearInterval;
global.doric = doric;
function initNativeEnvironment(source) {
return __awaiter(this, void 0, void 0, function* () {
// dev kit client
return new Promise((resolve, reject) => {
const devClient = new WebSocket('ws://localhost:7777');
devClient.on('open', () => {
console.log('Connectted Devkit on port', '7777');
devClient.send(JSON.stringify({
type: "D2C",
payload: {
cmd: "DEBUG_REQ",
source,
},
}));
});
devClient.on('message', (data) => {
console.log(data);
const msg = JSON.parse(data);
switch (msg.cwd) {
case "DEBUG_RES":
const contextId = msg.contextId;
if ((contextId === null || contextId === void 0 ? void 0 : contextId.length) > 0) {
resolve(contextId);
}
else {
reject(`Cannot find applicable context in client for source ${source}`);
}
break;
}
});
devClient.on('error', (error) => {
console.log(error);
reject(error);
});
});
});
}
global.Entry = function () {
var _a, _b, _c;
if (!!contextId) {
return Reflect.apply(doric.jsObtainEntry(contextId), doric, arguments);
}
else {
const jsFile = (_c = (_b = (_a = new Error().stack) === null || _a === void 0 ? void 0 : _a.split("\n").map(e => e.match(/at\s__decorate\s\((.*?)\)/)).find(e => !!e)) === null || _b === void 0 ? void 0 : _b[1].match(/(.*?\.js)/)) === null || _c === void 0 ? void 0 : _c[1];
if (!jsFile) {
throw new Error("Cannot find debugging file");
}
const source = path.basename(jsFile);
const args = arguments;
console.log(`Debugging ${source}`);
initNativeEnvironment(source).then(ret => {
contextId = ret;
console.log("debugging context id: " + contextId);
global.context = doric.jsObtainContext(contextId);
global.Entry = doric.jsObtainEntry(contextId);
Reflect.apply(doric.jsObtainEntry(contextId), doric, args);
}).catch(error => console.error(error));
return arguments[0];
}
};
// debug server
const debugServer = new WebSocket.Server({ port: 2080 });
debugServer.on('connection', function connection(ws) {
debugServer.on('connection', (ws) => {
console.log('connected');
ws.on('message', function incoming(message) {
ws.on('message', (message) => {
let messageObject = JSON.parse(message);
switch (messageObject.cmd) {
case "injectGlobalJSObject":

View File

@ -1537,6 +1537,8 @@ var doric = (function (exports) {
exports.jsRegisterModule = jsRegisterModule;
exports.jsReleaseContext = jsReleaseContext;
Object.defineProperty(exports, '__esModule', { value: true });
return exports;
}({}));
@ -2108,6 +2110,7 @@ function gravity() {
return new Gravity;
}
exports.LayoutSpec = void 0;
(function (LayoutSpec) {
/**
* Depends on what's been set on width or height.
@ -2528,10 +2531,12 @@ __decorate$2([
* See the License for the specific language governing permissions and
* limitations under the License.
*/
exports.RepeatMode = void 0;
(function (RepeatMode) {
RepeatMode[RepeatMode["RESTART"] = 1] = "RESTART";
RepeatMode[RepeatMode["REVERSE"] = 2] = "REVERSE";
})(exports.RepeatMode || (exports.RepeatMode = {}));
exports.FillMode = void 0;
(function (FillMode) {
/**
* The receiver is removed from the presentation when the animation is completed.
@ -2550,6 +2555,7 @@ __decorate$2([
*/
FillMode[FillMode["Both"] = 3] = "Both";
})(exports.FillMode || (exports.FillMode = {}));
exports.TimingFunction = void 0;
(function (TimingFunction) {
/**
* The system default timing function. Use this function to ensure that the timing of your animations matches that of most system animations.
@ -2829,6 +2835,7 @@ Color.YELLOW = new Color(0xFFFFFF00);
Color.CYAN = new Color(0xFF00FFFF);
Color.MAGENTA = new Color(0xFFFF00FF);
Color.TRANSPARENT = new Color(0);
exports.GradientOrientation = void 0;
(function (GradientOrientation) {
/** draw the gradient from the top to the bottom */
GradientOrientation[GradientOrientation["TOP_BOTTOM"] = 0] = "TOP_BOTTOM";
@ -2857,6 +2864,7 @@ var __decorate$3 = (undefined && undefined.__decorate) || function (decorators,
var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
exports.TruncateAt = void 0;
(function (TruncateAt) {
TruncateAt[TruncateAt["End"] = 0] = "End";
TruncateAt[TruncateAt["Middle"] = 1] = "Middle";
@ -2939,6 +2947,7 @@ var __decorate$4 = (undefined && undefined.__decorate) || function (decorators,
var __metadata$4 = (undefined && undefined.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
exports.ScaleType = void 0;
(function (ScaleType) {
ScaleType[ScaleType["ScaleToFill"] = 0] = "ScaleToFill";
ScaleType[ScaleType["ScaleAspectFit"] = 1] = "ScaleAspectFit";
@ -3396,12 +3405,14 @@ class FlexTypedValue {
}
}
FlexTypedValue.Auto = new FlexTypedValue(ValueType.Auto);
exports.FlexDirection = void 0;
(function (FlexDirection) {
FlexDirection[FlexDirection["COLUMN"] = 0] = "COLUMN";
FlexDirection[FlexDirection["COLUMN_REVERSE"] = 1] = "COLUMN_REVERSE";
FlexDirection[FlexDirection["ROW"] = 2] = "ROW";
FlexDirection[FlexDirection["ROW_REVERSE"] = 3] = "ROW_REVERSE";
})(exports.FlexDirection || (exports.FlexDirection = {}));
exports.Align = void 0;
(function (Align) {
Align[Align["AUTO"] = 0] = "AUTO";
Align[Align["FLEX_START"] = 1] = "FLEX_START";
@ -3412,6 +3423,7 @@ FlexTypedValue.Auto = new FlexTypedValue(ValueType.Auto);
Align[Align["SPACE_BETWEEN"] = 6] = "SPACE_BETWEEN";
Align[Align["SPACE_AROUND"] = 7] = "SPACE_AROUND";
})(exports.Align || (exports.Align = {}));
exports.Justify = void 0;
(function (Justify) {
Justify[Justify["FLEX_START"] = 0] = "FLEX_START";
Justify[Justify["CENTER"] = 1] = "CENTER";
@ -3420,25 +3432,30 @@ FlexTypedValue.Auto = new FlexTypedValue(ValueType.Auto);
Justify[Justify["SPACE_AROUND"] = 4] = "SPACE_AROUND";
Justify[Justify["SPACE_EVENLY"] = 5] = "SPACE_EVENLY";
})(exports.Justify || (exports.Justify = {}));
exports.Direction = void 0;
(function (Direction) {
Direction[Direction["INHERIT"] = 0] = "INHERIT";
Direction[Direction["LTR"] = 1] = "LTR";
Direction[Direction["RTL"] = 2] = "RTL";
})(exports.Direction || (exports.Direction = {}));
exports.PositionType = void 0;
(function (PositionType) {
PositionType[PositionType["RELATIVE"] = 0] = "RELATIVE";
PositionType[PositionType["ABSOLUTE"] = 1] = "ABSOLUTE";
})(exports.PositionType || (exports.PositionType = {}));
exports.Wrap = void 0;
(function (Wrap) {
Wrap[Wrap["NO_WRAP"] = 0] = "NO_WRAP";
Wrap[Wrap["WRAP"] = 1] = "WRAP";
Wrap[Wrap["WRAP_REVERSE"] = 2] = "WRAP_REVERSE";
})(exports.Wrap || (exports.Wrap = {}));
exports.OverFlow = void 0;
(function (OverFlow) {
OverFlow[OverFlow["VISIBLE"] = 0] = "VISIBLE";
OverFlow[OverFlow["HIDDEN"] = 1] = "HIDDEN";
OverFlow[OverFlow["SCROLL"] = 2] = "SCROLL";
})(exports.OverFlow || (exports.OverFlow = {}));
exports.Display = void 0;
(function (Display) {
Display[Display["FLEX"] = 0] = "FLEX";
Display[Display["NONE"] = 1] = "NONE";
@ -3652,6 +3669,7 @@ __decorate$a([
Property,
__metadata$a("design:type", Boolean)
], Input.prototype, "password", void 0);
exports.InputType = void 0;
(function (InputType) {
InputType[InputType["Default"] = 0] = "Default";
InputType[InputType["Number"] = 1] = "Number";
@ -4107,6 +4125,7 @@ function notification(context) {
};
}
exports.StatusBarMode = void 0;
(function (StatusBarMode) {
StatusBarMode[StatusBarMode["LIGHT"] = 0] = "LIGHT";
StatusBarMode[StatusBarMode["DARK"] = 1] = "DARK";

File diff suppressed because one or more lines are too long