File size: 2,332 Bytes
bc20498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import fetch from '@webreflection/fetch';

import { interpreter } from './interpreters.js';
import { absoluteURL, resolve } from './utils.js';
import { parse } from './toml.js';

// REQUIRES INTEGRATION TEST
/* c8 ignore start */
export const getConfigURLAndType = (config, configURL = './config.txt') => {
    let type = typeof config;
    if (type === 'string' && /\.(json|toml|txt)$/.test(config))
        type = RegExp.$1;
    else
        config = configURL;
    return [absoluteURL(config), type];
};

const parseString = config => {
    try {
        return JSON.parse(config);
    }
    // eslint-disable-next-line no-unused-vars
    catch (_) {
        return parse(config);
    }
};
/* c8 ignore stop */

/**
 * Parse a generic config if it came from an attribute either as URL
 * or as a serialized string. In XWorker case, accepts a pre-defined
 * options to use as it is to avoid needing at all a fetch operation.
 * In latter case, config will be suffixed as `config.txt`.
 * @param {string} id the interpreter name @ version identifier
 * @param {string | object} config optional config file to parse
 * @param {string} [configURL] optional config URL if config is not string
 * @param {object} [options] optional options used to bootstrap XWorker
 * @returns
 */
export const getRuntime = (id, config, configURL, options = {}) => {
    if (config) {
        // REQUIRES INTEGRATION TEST
        /* c8 ignore start */
        const [absolute, type] = getConfigURLAndType(config, configURL);
        if (type === 'json') {
            options = fetch(absolute).json();
        } else if (type === 'toml') {
            options = fetch(absolute).text().then(parse);
        } else if (type === 'string') {
            options = parseString(config);
        } else if (type === 'object' && config) {
            options = config;
        } else if (type === 'txt' && typeof options === 'string') {
            options = parseString(options);
        }
        config = absolute;
        /* c8 ignore stop */
    }
    return resolve(options).then(options => interpreter[id](options, config));
};

/**
 * @param {string} type the interpreter type
 * @param {string} [version] the optional interpreter version
 * @returns
 */
export const getRuntimeID = (type, version = '') =>
    `${type}@${version}`.replace(/@$/, '');