avocado-old/packages/core/hook/loader.js

60 lines
1.4 KiB
JavaScript
Raw Normal View History

2019-11-22 02:13:32 -06:00
const path = require('path');
2019-11-20 00:53:35 -06:00
const glob = require('glob');
const {getOptions} = require('loader-utils');
const validateOptions = require('schema-utils');
2019-11-22 02:13:32 -06:00
const {lookupSourcePaths} = require('../webpack/util');
2019-11-20 00:53:35 -06:00
const schema = {
type: 'object',
properties: {
paths: {
items: {
type: 'string',
},
type: 'array',
},
},
required: [
'paths',
],
};
// Dynamically require all traits.
module.exports = function(source) {
const options = getOptions(this);
// Validate schema.
2019-11-22 02:13:32 -06:00
validateOptions(schema, options, '[avocado] Hooks');
2019-11-20 00:53:35 -06:00
// Extract options.
2019-11-22 02:13:32 -06:00
const {paths, root} = options;
2019-11-20 00:53:35 -06:00
// Build registers.
2019-11-22 02:13:32 -06:00
const sourcePaths = lookupSourcePaths(paths, 'hooks.js');
2019-11-20 00:53:35 -06:00
const registers = sourcePaths.map((sourcePath) => {
2019-11-22 02:13:32 -06:00
const relativePath = path.relative(root, sourcePath);
2019-11-20 00:53:35 -06:00
const parts = relativePath.split('/');
// Chop off basename.
parts.pop();
// Module or local?
let importDirectory;
2019-11-22 02:13:32 -06:00
if ('node_modules' === parts[0]) {
2019-11-20 00:53:35 -06:00
importDirectory = parts.slice(1).join('/');
}
else {
importDirectory = `./${parts.join('/')}`;
}
// Register hooks.
const importPath = `${importDirectory}/hooks`;
return [
`registerHooks('${importDirectory}', require('${importPath}'));`,
].join('\n');
});
// Import trait registry first.
const output = [
`import {registerHooks} from '@avocado/core/hook/registry'`,
'',
...registers
].join('\n');
return output;
}