Keep isolateRefs in context

This commit is contained in:
Adria Navarro 2024-01-24 14:02:34 +01:00
parent d7b5aa08db
commit bc7825dc93
2 changed files with 70 additions and 56 deletions

View File

@ -1,5 +1,5 @@
import { IdentityContext } from "@budibase/types"
import { Isolate, Context } from "isolated-vm"
import { Isolate, Context, Module } from "isolated-vm"
// keep this out of Budibase types, don't want to expose context info
export type ContextMap = {
@ -10,6 +10,9 @@ export type ContextMap = {
isScim?: boolean
automationId?: string
isMigrating?: boolean
jsIsolate?: Isolate
jsContext?: Context
isolateRefs?: {
jsIsolate: Isolate
jsContext: Context
helpersModule: Module
}
}

View File

@ -7,16 +7,20 @@ import fs from "fs"
import url from "url"
import crypto from "crypto"
export function init() {
const helpersSource = fs.readFileSync(
`${require.resolve("@budibase/string-templates/index-helpers")}`,
"utf8"
)
export function init() {
setJSRunner((js: string, ctx: Record<string, any>) => {
return tracer.trace("runJS", {}, span => {
const bbCtx = context.getCurrentContext() || {}
let { jsIsolate = new ivm.Isolate({ memoryLimit: 64 }) } = bbCtx
let { jsContext = jsIsolate.createContextSync() } = bbCtx
const bbCtx = context.getCurrentContext()!
const isolateRefs = bbCtx.isolateRefs
if (!isolateRefs) {
const jsIsolate = new ivm.Isolate({ memoryLimit: 64 })
const jsContext = jsIsolate.createContextSync()
const injectedRequire = `const require = function(val){
switch (val) {
@ -56,9 +60,11 @@ export function init() {
global.setSync(
"cryptoRandomUUIDCb",
new ivm.Callback((...params: Parameters<typeof crypto.randomUUID>) => {
new ivm.Callback(
(...params: Parameters<typeof crypto.randomUUID>) => {
return crypto.randomUUID(...params)
})
}
)
)
helpersModule.instantiateSync(jsContext, specifier => {
@ -86,6 +92,11 @@ export function init() {
global.setSync(key, value)
}
bbCtx.isolateRefs = { jsContext, jsIsolate, helpersModule }
}
let { jsIsolate, jsContext, helpersModule } = bbCtx.isolateRefs!
const script = jsIsolate.compileModuleSync(
`import helpers from "compiled_module";${js};cb(run());`,
{}
@ -100,7 +111,7 @@ export function init() {
})
let result
global.setSync(
jsContext.global.setSync(
"cb",
new ivm.Callback((value: any) => {
result = value