1 | #!/usr/bin/env node
|
2 |
|
3 | import _hyperscript from '../lib/core.js'
|
4 | const fs = require('fs');
|
5 | const path = require('path')
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | const hsExt = '._hs';
|
11 |
|
12 | global.require = require;
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | function run(modulePath) {
|
19 | modulePath = path.resolve(modulePath);
|
20 | const args = { module: { dir: path.dirname(modulePath), id: modulePath } }
|
21 | return fs.promises.readFile(modulePath, { encoding: 'utf-8' })
|
22 | .then(code => _hyperscript.evaluate(code, {}, args))
|
23 | .catch(e => console.error("Cannot execute file: ", e));
|
24 | }
|
25 |
|
26 | _hyperscript.addFeature('require', (parser, runtime, tokens) => {
|
27 | if (!tokens.matchToken('require')) return;
|
28 |
|
29 | let id = parser.requireElement('nakedString', tokens)
|
30 |
|
31 | .evaluate({});
|
32 |
|
33 | let name = id;
|
34 | if (tokens.matchToken('as')) {
|
35 | name = tokens.requireTokenType('IDENTIFIER').value;
|
36 | } else {
|
37 | name = path.basename(id)
|
38 | .replace(/\.[^\.]*$/, '')
|
39 | }
|
40 |
|
41 | return {
|
42 | install(target, source, args) {
|
43 | if (id.startsWith('./') || id.startsWith('../')) {
|
44 | id = path.join(args.module.dir, id);
|
45 | }
|
46 |
|
47 | let mod;
|
48 | if (id.endsWith(hsExt)) mod = run(id);
|
49 | if (fs.existsSync(id + hsExt)) mod = run(id + hsExt);
|
50 | else mod = require(id);
|
51 | runtime.assignToNamespace(target, [], name, mod);
|
52 |
|
53 | }
|
54 | }
|
55 | })
|
56 |
|
57 | run(process.argv[2])
|