@velcro/runner
Version:
Opinionated tool for easily bundling and running code from anywhere
83 lines (77 loc) • 3.24 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var bundler = require('@velcro/bundler');
var common = require('@velcro/common');
var resolver = require('@velcro/resolver');
var strategyCdn = require('@velcro/strategy-cdn');
var strategyCompound = require('@velcro/strategy-compound');
var strategyMemory = require('@velcro/strategy-memory');
const defaultExtensions = ['.js', '.json'];
const defaultPackageMain = ['browser', 'main'];
async function build(code, options) {
const entrypointPath = `index.js`;
const cdnStrategy = options.cdn === 'unpkg'
? strategyCdn.CdnStrategy.forUnpkg(options.readUrl)
: strategyCdn.CdnStrategy.forJsDelivr(options.readUrl);
const memoryStrategy = new strategyMemory.MemoryStrategy({
[entrypointPath]: code,
['package.json']: JSON.stringify({
name: '@@velcro/execute',
version: '0.0.0',
dependencies: options.dependencies,
}),
}, common.Uri.parse(`velcro://${Math.random().toString(16).slice(2)}/`));
const entrypointUri = memoryStrategy.uriForPath(entrypointPath);
const compoundStrategy = new strategyCompound.CompoundStrategy({ strategies: [cdnStrategy, memoryStrategy] });
const resolver$1 = new resolver.Resolver(compoundStrategy, {
extensions: options.extensions || defaultExtensions,
packageMain: options.packageMain || defaultPackageMain,
});
const graphBuilder = new bundler.GraphBuilder({
external: options.external,
resolver: resolver$1,
nodeEnv: options.nodeEnv || 'development',
plugins: options.plugins,
});
const build = graphBuilder.build([entrypointUri]);
const graph = await build.done;
const [chunk] = graph.splitChunks();
const output = chunk.buildForStaticRuntime({
injectRuntime: true,
});
return { entrypoints: output.entrypoints, output };
}
async function execute(code, options) {
if (options.injectModules) {
const injectedModuleSpecs = new Set(Object.keys(options.injectModules));
const optionsExternal = options.external;
const isExternal = (dependency, fromSourceModule) => {
if (injectedModuleSpecs.has(dependency.spec)) {
return true;
}
return typeof optionsExternal === 'function'
? optionsExternal(dependency, fromSourceModule)
: false;
};
options.external = isExternal;
}
const { entrypoints, output } = await build(code, options);
const codeWithStart = `${output.code}\n\nreturn Velcro.runtime;\n`;
const runtimeCode = options.sourceMap
? `${codeWithStart}\n//# sourceMappingURL=${output.sourceMapDataUri}`
: codeWithStart;
const runtimeFn = new Function(runtimeCode);
const velcro = runtimeFn();
if (options.injectModules) {
for (const id in options.injectModules) {
velcro.inject(id, options.injectModules[id]);
}
}
const result = velcro.require(entrypoints[0].toString());
return result;
}
const version = '0.56.2';
exports.build = build;
exports.execute = execute;
exports.version = version;
//# sourceMappingURL=index.js.map