pull/3/head
Zef Hemel 2022-05-13 17:05:52 +02:00
parent 3c5048ac25
commit 7d01f77318
12 changed files with 70 additions and 55 deletions

View File

@ -12,7 +12,7 @@ import { compile, sandboxCompileModule } from "../compile";
async function bundle( async function bundle(
manifestPath: string, manifestPath: string,
sourceMaps: boolean, debug: boolean,
excludeModules: string[] excludeModules: string[]
) { ) {
const rootPath = path.dirname(manifestPath); const rootPath = path.dirname(manifestPath);
@ -40,7 +40,7 @@ async function bundle(
def.code = await compile( def.code = await compile(
filePath, filePath,
jsFunctionName, jsFunctionName,
sourceMaps, debug,
allModulesToExclude allModulesToExclude
); );
delete def.path; delete def.path;

View File

@ -35,7 +35,7 @@ export async function compile(
format: "iife", format: "iife",
globalName: "mod", globalName: "mod",
platform: "browser", platform: "browser",
sourcemap: false, //sourceMap ? "inline" : false, sourcemap: false, //debug ? "inline" : false,
minify: !debug, minify: !debug,
outfile: outFile, outfile: outFile,
metafile: true, metafile: true,
@ -45,7 +45,7 @@ export async function compile(
if (meta) { if (meta) {
let text = await esbuild.analyzeMetafile(result.metafile); let text = await esbuild.analyzeMetafile(result.metafile);
console.log("Bundle info for", functionName, text); // console.log("Bundle info for", functionName, text);
} }
let jsCode = (await readFile(outFile)).toString(); let jsCode = (await readFile(outFile)).toString();
@ -77,6 +77,7 @@ export async function sandboxCompile(
filename: string, filename: string,
code: string, code: string,
functionName?: string, functionName?: string,
debug: boolean = false,
installModules: string[] = [], installModules: string[] = [],
globalModules: string[] = [] globalModules: string[] = []
): Promise<string> { ): Promise<string> {
@ -102,11 +103,10 @@ export async function sandboxCompile(
} }
await writeFile(`${tmpDir}/${filename}`, code); await writeFile(`${tmpDir}/${filename}`, code);
let jsCode = await compile( let jsCode = await compile(
`${tmpDir}/${filename}`, `${tmpDir}/${filename}`,
functionName, functionName,
false, debug,
globalModules globalModules
); );
await rm(tmpDir, { recursive: true }); await rm(tmpDir, { recursive: true });
@ -127,6 +127,7 @@ export async function sandboxCompileModule(
// `export * from "${cleanModulesName}${path ? path : ""}";`, // `export * from "${cleanModulesName}${path ? path : ""}";`,
`module.exports = require("${cleanModulesName}${path ? path : ""}");`, `module.exports = require("${cleanModulesName}${path ? path : ""}");`,
undefined, undefined,
true,
[modulePart], [modulePart],
globalModules globalModules
); );

View File

@ -120,10 +120,12 @@ parentPort.on("message", (data: any) => {
result: result && JSON.parse(JSON.stringify(result)), result: result && JSON.parse(JSON.stringify(result)),
}); });
} catch (e: any) { } catch (e: any) {
// console.error("Error caught", e, "Stack", e.stack);
parentPort.postMessage({ parentPort.postMessage({
type: "result", type: "result",
id: data.id, id: data.id,
error: e.message, error: e.message,
stack: e.stack,
}); });
} }
break; break;

View File

@ -96,8 +96,9 @@ self.addEventListener("message", (event: { data: WorkerMessage }) => {
type: "result", type: "result",
id: data.id, id: data.id,
error: e.message, error: e.message,
stack: e.stack,
}); });
console.error("Error invoking function", data.name, e.message); // console.error("Error invoking function", data.name, e.message);
// throw e; // throw e;
} }

View File

@ -13,6 +13,7 @@ export type ControllerMessage = {
name?: string; name?: string;
args?: any[]; args?: any[];
error?: string; error?: string;
stack?: string;
level?: LogLevel; level?: LogLevel;
message?: string; message?: string;
result?: any; result?: any;

View File

@ -114,7 +114,10 @@ export class Sandbox {
let resultCbs = this.outstandingInvocations.get(data.id!); let resultCbs = this.outstandingInvocations.get(data.id!);
this.outstandingInvocations.delete(data.id!); this.outstandingInvocations.delete(data.id!);
if (data.error) { if (data.error) {
resultCbs && resultCbs.reject(new Error(data.error)); resultCbs &&
resultCbs.reject(
new Error(`${data.error}\nStack trace: ${data.stack}`)
);
} else { } else {
resultCbs && resultCbs.resolve(data.result); resultCbs && resultCbs.resolve(data.result);
} }

View File

@ -1,14 +1,7 @@
import { compile } from "../compile"; import { sandboxCompile, sandboxCompileModule } from "../compile";
import { SysCallMapping } from "../system"; import { SysCallMapping } from "../system";
import { tmpdir } from "os";
import { mkdir, rm, symlink, writeFile } from "fs/promises";
import { nodeModulesDir } from "../environments/node_sandbox";
const exposedModules = [ import globalModules from "../../common/dist/global.plug.json";
"@silverbulletmd/plugos-silverbullet-syscall",
"@plugos/plugos-syscall",
"yaml",
];
import * as ts from "typescript"; import * as ts from "typescript";
@ -69,36 +62,26 @@ export function esbuildSyscalls(): SysCallMapping {
ctx, ctx,
filename: string, filename: string,
code: string, code: string,
functionName?: string functionName?: string,
excludeModules: string[] = []
): Promise<string> => { ): Promise<string> => {
let tmpDir = await prepareCompileEnv(filename, code); return await sandboxCompile(
let jsCode = await compile(`${tmpDir}/${filename}`, functionName, false, [ filename,
"yaml", code,
"handlebars", functionName,
]); true,
await rm(tmpDir, { recursive: true }); [],
return jsCode; [...Object.keys(globalModules.dependencies), ...excludeModules]
);
},
"esbuild.compileModule": async (
ctx,
moduleName: string
): Promise<string> => {
return await sandboxCompileModule(
moduleName,
Object.keys(globalModules.dependencies)
);
}, },
}; };
} }
async function prepareCompileEnv(filename: string, code: string) {
let tmpDir = `${tmpdir()}/plugos-${Math.random()}`;
await mkdir(tmpDir, { recursive: true });
const srcNodeModules = `${nodeModulesDir}/node_modules`;
const targetNodeModules = `${tmpDir}/node_modules`;
await mkdir(`${targetNodeModules}/@silverbulletmd`, { recursive: true });
await mkdir(`${targetNodeModules}/@plugos`, { recursive: true });
for (const exposedModule of exposedModules) {
await symlink(
`${srcNodeModules}/${exposedModule}`,
`${targetNodeModules}/${exposedModule}`,
"dir"
);
}
await writeFile(`${tmpDir}/${filename}`, code);
return tmpDir;
}

View File

@ -8,7 +8,7 @@
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"generate": "lezer-generator query/query.grammar -o query/parse-query.js", "generate": "lezer-generator query/query.grammar -o query/parse-query.js",
"watch": "plugos-bundle --dist ../common/dist global.plug.yaml && plugos-bundle -w --dist dist --exclude @lezer/lr yaml handlebars -- */*.plug.yaml", "watch": "plugos-bundle --dist ../common/dist global.plug.yaml && plugos-bundle --debug -w --dist dist --exclude @lezer/lr yaml handlebars -- */*.plug.yaml",
"build": "plugos-bundle --dist ../common/dist global.plug.yaml && plugos-bundle --dist dist --exclude @lezer/lr yaml handlebars -- */*.plug.yaml", "build": "plugos-bundle --dist ../common/dist global.plug.yaml && plugos-bundle --dist dist --exclude @lezer/lr yaml handlebars -- */*.plug.yaml",
"test": "jest build/test" "test": "jest build/test"
}, },

View File

@ -24,7 +24,9 @@ functions:
compileJS: compileJS:
path: "./plugmanager.ts:compileJS" path: "./plugmanager.ts:compileJS"
env: server env: server
compileModule:
path: "./plugmanager.ts:compileModule"
env: server
getPlugPlugMd: getPlugPlugMd:
path: "./plugmanager.ts:getPlugPlugMd" path: "./plugmanager.ts:getPlugPlugMd"
events: events:

View File

@ -5,6 +5,7 @@ import {
findNodeOfType, findNodeOfType,
} from "@silverbulletmd/common/tree"; } from "@silverbulletmd/common/tree";
import { import {
flashNotification,
getText, getText,
hideBhs, hideBhs,
showBhs, showBhs,
@ -84,6 +85,13 @@ async function compileDefinition(text: string): Promise<Manifest> {
throw new Error("No code found"); throw new Error("No code found");
} }
manifest.dependencies = manifest.dependencies || {};
for (let [dep, depSpec] of Object.entries(manifest.dependencies)) {
let compiled = await invokeFunction("server", "compileModule", depSpec);
manifest.dependencies![dep] = compiled;
}
manifest.functions = manifest.functions || {}; manifest.functions = manifest.functions || {};
for (let [name, func] of Object.entries(manifest.functions)) { for (let [name, func] of Object.entries(manifest.functions)) {
@ -92,7 +100,8 @@ async function compileDefinition(text: string): Promise<Manifest> {
"compileJS", "compileJS",
`file.${language}`, `file.${language}`,
code, code,
name name,
Object.keys(manifest.dependencies)
); );
func.code = compiled; func.code = compiled;
} }
@ -105,9 +114,21 @@ async function compileDefinition(text: string): Promise<Manifest> {
export async function compileJS( export async function compileJS(
filename: string, filename: string,
code: string, code: string,
functionName: string functionName: string,
excludeModules: string[]
): Promise<string> { ): Promise<string> {
return self.syscall("esbuild.compile", filename, code, functionName); // console.log("Compiling JS", filename, excludeModules);
return self.syscall(
"esbuild.compile",
filename,
code,
functionName,
excludeModules
);
}
export async function compileModule(moduleName: string): Promise<string> {
return self.syscall("esbuild.compileModule", moduleName);
} }
async function listPlugs(): Promise<string[]> { async function listPlugs(): Promise<string[]> {
@ -122,7 +143,9 @@ export async function listCommand() {
} }
export async function updatePlugsCommand() { export async function updatePlugsCommand() {
flashNotification("Updating plugs...");
await invokeFunction("server", "updatePlugs"); await invokeFunction("server", "updatePlugs");
flashNotification("And... done!");
await reloadPlugs(); await reloadPlugs();
} }
@ -137,7 +160,6 @@ export async function updatePlugs() {
return; return;
} }
let plugYaml = codeTextNode.children![0].text; let plugYaml = codeTextNode.children![0].text;
console.log("YAML", YAML);
let plugList = YAML.parse(plugYaml!); let plugList = YAML.parse(plugYaml!);
console.log("Plug YAML", plugList); console.log("Plug YAML", plugList);
let allPlugNames: string[] = []; let allPlugNames: string[] = [];

View File

@ -339,7 +339,7 @@ export class ExpressServer {
res.send(result); res.send(result);
} catch (e: any) { } catch (e: any) {
res.status(500); res.status(500);
console.log("Error invoking function", e); // console.log("Error invoking function", e);
return res.send(e.message); return res.send(e.message);
} }
} }

View File

@ -603,7 +603,7 @@ export class Editor {
editor!.focus(); editor!.focus();
if (cmd) { if (cmd) {
cmd.run().catch((e) => { cmd.run().catch((e) => {
console.error("Error running command", e); console.error("Error running command", e.message);
}); });
} }
}} }}