|
| 1 | +import { IO, Runtime, Value, infer } from '@commontools/runtime'; |
| 2 | +console.log('wow') |
| 3 | + |
| 4 | +const EXAMPLE_MODULE_JS = ` |
| 5 | +import { read, write } from 'common:io/state@0.0.1'; |
| 6 | +
|
| 7 | +export class Body { |
| 8 | + run() { |
| 9 | + console.log('Running!'); |
| 10 | + const foo = read('foo'); |
| 11 | + console.log('Reference:', foo); |
| 12 | + const value = foo?.deref(); |
| 13 | + console.log('Value:', value); |
| 14 | + } |
| 15 | +} |
| 16 | +
|
| 17 | +export const module = { |
| 18 | + Body, |
| 19 | +
|
| 20 | + create() { |
| 21 | + console.log('Creating!'); |
| 22 | + return new Body(); |
| 23 | + } |
| 24 | +};`; |
| 25 | + |
| 26 | +class LocalStorageIO implements IO { |
| 27 | + reset() { |
| 28 | + localStorage.clear(); |
| 29 | + } |
| 30 | + |
| 31 | + read(key: string): Value | undefined { |
| 32 | + console.log(`Reading '${key}' from local storage`); |
| 33 | + let rawValue = localStorage.getItem(key); |
| 34 | + return infer(rawValue); |
| 35 | + } |
| 36 | + |
| 37 | + write(key: string, value: Value): void { |
| 38 | + console.log(`Writing '${key} => ${value.val}' to local storage`); |
| 39 | + // YOLO (don't do it this way actually) |
| 40 | + localStorage.setItem(key, value.val); |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +export const demo = async () => { |
| 45 | + const rt = new Runtime(); |
| 46 | + const io = new LocalStorageIO(); |
| 47 | + |
| 48 | + io.reset(); |
| 49 | + |
| 50 | + const module = await rt.eval('text/javascript', EXAMPLE_MODULE_JS, io); |
| 51 | + |
| 52 | + console.log(`Setting 'foo => bar' at the host level`); |
| 53 | + io.write('foo', infer('bar')); |
| 54 | + |
| 55 | + console.log('Running the module:'); |
| 56 | + module.run(); |
| 57 | +}; |
0 commit comments