UNPKG

1.67 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3import _hyperscript from '../lib/core.js'
4const fs = require('fs');
5const path = require('path')
6
7/**
8 * File extension for _hyperscript files
9 */
10const hsExt = '._hs';
11
12global.require = require; // Allow importing modules from within hyperscript
13
14/**
15 *
16 * @param {String} modulePath
17 */
18function 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 /** @type {string} */
29 let id = parser.requireElement('nakedString', tokens)
30 // @ts-ignore
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(/\.[^\.]*$/, '') // remove extension
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 //console.log(id, name, mod.toString(), target.hyperscriptFeatures);
53 }
54 }
55})
56
57run(process.argv[2])