git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 7465ee54b512e6772d88465794c551333e42ecfe

Files: 7465ee54b512e6772d88465794c551333e42ecfe / index.js

1983 bytesRaw
1const Vertex = require('./deps/kernelVertex')
2// The Kernel Exposes this Interface to VM instances it makes
3const Interface = require('./interface.js')
4const InterfaceAPI = require('./interfaceAPI.js')
5const Environment = require('./environment.js')
6
7module.exports = class Kernel {
8 constructor (opts = {}) {
9 this.state = opts.state || new Vertex()
10 this.parent = opts.parent
11
12 // if code is bound to this kernel then create the interfaceAPI and the
13 // imports
14 if (opts.code) {
15 this.interfaceAPI = new InterfaceAPI(opts.code)
16 this.imports = this.buildImports(opts.interfaces)
17 }
18 }
19
20 /**
21 * Builds a import map with an array of given interfaces
22 */
23 buildImports (interfaces = [Interface]) {
24 return interfaces.reduce((obj, Interface) => {
25 obj[Interface.name] = new Interface(this.interfaceAPI).exports
26 return obj
27 }, {})
28 }
29
30 /**
31 * run the kernels code with a given enviroment
32 * The Kernel Stores all of its state in the Environment. The Interface is used
33 * to by the VM to retrive infromation from the Environment.
34 */
35 async run (environment = new Environment({state: this.state}), imports = this.imports) {
36 await this.interfaceAPI.run(environment, imports)
37 return environment
38 }
39
40 async messageReceiver (message) {
41 // let the code handle the message if there is code
42 if (this.code) {
43 const environment = new Environment(message)
44 let result = await this.run(environment)
45 if (!result.execption) {
46 this.state = result.state
47 }
48 } else if (message.to.length) {
49 // else forward the message on to the destination contract
50 let [vertex, done] = await this.state.update(message.to)
51 message.to = []
52 await vertex.kernel.messageReceiver(message)
53 done(vertex)
54 }
55 }
56
57 copy () {
58 return new Kernel({
59 state: this.state.copy(),
60 code: this.code,
61 interfaces: this.interfaces,
62 parent: this.parent
63 })
64 }
65}
66

Built with git-ssb-web