Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More

babel-plugin-codegen

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

babel-plugin-codegen - npm Package Compare versions

Comparing version 1.2.1 to 1.3.0

'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var _require = require('./replace'),
asProgram = _require.asProgram,
asIdentifier = _require.asIdentifier,
asImportDeclaration = _require.asImportDeclaration;
function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
var _require2 = require('./helpers'),
isCodegenComment = _require2.isCodegenComment,
looksLike = _require2.looksLike;
var p = require('path');
var getReplacement = require('./get-replacement');
var replace = require('./replace');
module.exports = codegenPlugin;

@@ -26,26 +27,14 @@

if (!isCodegen) {
return;
if (isCodegen) {
comments.find(isCodegenComment).value = ' this file was codegened';
asProgram(transformFromAst, path, filename);
}
comments.find(isCodegenComment).value = ' this file was codegened';
var _transformFromAst = transformFromAst(path.node),
string = _transformFromAst.code;
var replacement = getReplacement({ string, filename });
path.node.body = Array.isArray(replacement) ? replacement : [replacement];
},
TaggedTemplateExpression(path, _ref3) {
Identifier(path, _ref3) {
var filename = _ref3.file.opts.filename;
var isCodegen = path.node.tag.name === 'codegen';
if (!isCodegen) {
return;
var isCodegen = path.node.name === 'codegen';
if (isCodegen) {
asIdentifier(path, filename);
}
var string = path.get('quasi').evaluate().value;
if (!string) {
throw new Error('Unable to determine the value of your codegen string');
}
replace({ path, string, filename });
},

@@ -64,119 +53,8 @@ ImportDeclaration(path, _ref4) {

});
if (!isCodegen) {
return;
if (isCodegen) {
asImportDeclaration(path, filename);
}
var codegenComment = path.node.source.leadingComments.find(isCodegenComment).value.trim();
var args = void 0;
if (codegenComment !== 'codegen') {
args = codegenComment.replace(/codegen\((.*)\)/, '$1').trim();
}
replace({
path,
string: `
try {
// allow for transpilation of required modules
require('babel-register')
} catch (e) {
// ignore error
}
var mod = require('${path.node.source.value}');
mod = mod && mod.__esModule ? mod.default : mod
${args ? `mod = mod(${args})` : ''}
module.exports = mod
`,
filename
});
},
CallExpression(path, _ref5) {
var filename = _ref5.file.opts.filename;
var isCodegen = looksLike(path, {
node: {
callee: {
type: 'MemberExpression',
object: { name: 'codegen' },
property: { name: 'require' }
}
}
});
if (!isCodegen) {
return;
}
var _path$get = path.get('arguments'),
_path$get2 = _toArray(_path$get),
source = _path$get2[0],
args = _path$get2.slice(1);
var string = resolveModuleToString({ args, filename, source });
var replacement = getReplacement.stringToAST(string);
if (!replacement) {
path.remove();
} else if (Array.isArray(replacement)) {
path.replaceWithMultiple(replacement);
} else {
path.replaceWith(replacement);
}
}
}
};
}
function resolveModuleToString(_ref6) {
var args = _ref6.args,
filename = _ref6.filename,
source = _ref6.source;
var argValues = args.map(function (a) {
var result = a.evaluate();
if (!result.confident) {
throw new Error('codegen cannot determine the value of an argument in codegen.require');
}
return result.value;
});
var absolutePath = p.join(p.dirname(filename), source.node.value);
try {
// allow for transpilation of required modules
require('babel-register');
} catch (e) {
// ignore error
}
var mod = require(absolutePath);
mod = mod && mod.__esModule ? mod.default : mod;
if (argValues.length) {
if (typeof mod !== 'function') {
throw new Error(`\`codegen.require\`-ed module (${source.node.value}) cannot accept arguments because it does not export a function. You passed the arguments: ${argValues.join(', ')}`);
}
mod = mod.apply(undefined, _toConsumableArray(argValues));
}
return mod;
}
function isCodegenComment(comment) {
var normalisedComment = comment.value.trim().split(' ')[0].trim();
return normalisedComment.startsWith('codegen') || normalisedComment.startsWith('@codegen');
}
function looksLike(a, b) {
return a && b && Object.keys(b).every(function (bKey) {
var bVal = b[bKey];
var aVal = a[bKey];
if (typeof bVal === 'function') {
return bVal(aVal);
}
return isPrimitive(bVal) ? bVal === aVal : looksLike(aVal, bVal);
});
}
function isPrimitive(val) {
// eslint-disable-next-line
return val == null || /^[sbn]/.test(typeof val);
}
/*
eslint
complexity: ["error", 8],
import/no-unassigned-import: "off",
import/no-dynamic-require: "off",
*/
}

@@ -7,3 +7,4 @@ 'use strict';

var replace = require('./replace');
var _require2 = require('./replace'),
asIdentifier = _require2.asIdentifier;

@@ -16,55 +17,8 @@ module.exports = createMacro(codegenMacros);

var filename = state.file.opts.filename;
references.default.forEach(function (referencePath) {
if (referencePath.parentPath.type === 'TaggedTemplateExpression') {
asTag(referencePath.parentPath.get('quasi'), state);
} else if (referencePath.parentPath.type === 'CallExpression') {
asFunction(referencePath.parentPath.get('arguments'), state);
} else if (referencePath.parentPath.type === 'JSXOpeningElement') {
asJSX({
attributes: referencePath.parentPath.get('attributes'),
children: referencePath.parentPath.parentPath.get('children')
}, state);
if (asIdentifier(referencePath, filename) === false) {
throw referencePath.buildCodeFrameError('codegen macro must be used as a tagged template literal, function, jsx, or .require call', Error);
}
}
// TODO: throw a helpful error message
);
}
function asTag(quasiPath, _ref2) {
var filename = _ref2.file.opts.filename;
var string = quasiPath.parentPath.get('quasi').evaluate().value;
replace({
path: quasiPath.parentPath,
string,
filename
});
}
function asFunction(argumentsPaths, _ref3) {
var filename = _ref3.file.opts.filename;
var string = argumentsPaths[0].evaluate().value;
replace({
path: argumentsPaths[0].parentPath,
string,
filename
});
}
// eslint-disable-next-line no-unused-vars
function asJSX(_ref4, _ref5) {
var attributes = _ref4.attributes,
children = _ref4.children;
var filename = _ref5.file.opts.filename;
var string = children[0].node.expression.value;
if (children[0].node.expression.type === 'TemplateLiteral') {
string = children[0].get('expression').evaluate().value;
}
replace({
path: children[0].parentPath,
string,
filename
});
}
'use strict';
var getReplacement = require('./get-replacement');
function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
module.exports = replace;
var _require = require('./helpers'),
getReplacement = _require.getReplacement,
replace = _require.replace,
resolveModuleToString = _require.resolveModuleToString,
stringToAST = _require.stringToAST,
isCodegenComment = _require.isCodegenComment,
isPropertyCall = _require.isPropertyCall;
function replace(_ref) {
var path = _ref.path,
string = _ref.string,
filename = _ref.filename;
module.exports = {
asTag,
asJSX,
asFunction,
asProgram,
asImportCall,
asImportDeclaration,
asIdentifier
};
var replacement = getReplacement({
string,
function asProgram(transformFromAst, path, filename) {
var _transformFromAst = transformFromAst(path.node),
string = _transformFromAst.code;
var replacement = getReplacement({ string, filename });
path.node.body = Array.isArray(replacement) ? replacement : [replacement];
}
function asImportDeclaration(path, filename) {
var codegenComment = path.node.source.leadingComments.find(isCodegenComment).value.trim();
var args = void 0;
if (codegenComment !== 'codegen') {
args = codegenComment.replace(/codegen\((.*)\)/, '$1').trim();
}
replace({
path,
string: `
try {
// allow for transpilation of required modules
require('babel-register')
} catch (e) {
// ignore error
}
var mod = require('${path.node.source.value}');
mod = mod && mod.__esModule ? mod.default : mod
${args ? `mod = mod(${args})` : ''}
module.exports = mod
`,
filename
});
}
function asIdentifier(path, filename) {
var targetPath = path.parentPath;
switch (targetPath.type) {
case 'TaggedTemplateExpression':
{
return asTag(targetPath, filename);
}
case 'CallExpression':
{
var isCallee = targetPath.get('callee') === path;
if (isCallee) {
return asFunction(targetPath, filename);
} else {
return false;
}
}
case 'JSXOpeningElement':
{
var jsxElement = targetPath.parentPath;
return asJSX(jsxElement, filename);
}
case 'JSXClosingElement':
{
// ignore the closing element
// but don't mark as unhandled (return false)
// we already handled the opening element
return true;
}
case 'MemberExpression':
{
var callPath = targetPath.parentPath;
var isRequireCall = isPropertyCall(callPath, 'require');
if (isRequireCall) {
return asImportCall(callPath, filename);
} else {
return false;
}
}
default:
{
return false;
}
}
}
function asImportCall(path, filename) {
var _path$get = path.get('arguments'),
_path$get2 = _toArray(_path$get),
source = _path$get2[0],
args = _path$get2.slice(1);
var string = resolveModuleToString({ args, filename, source });
var replacement = stringToAST(string);
if (!replacement) {

@@ -23,2 +116,38 @@ path.remove();

}
}
}
function asTag(path, filename) {
var string = path.get('quasi').evaluate().value;
if (!string) {
throw path.buildCodeFrameError('Unable to determine the value of your codegen string', Error);
}
replace({ path, string, filename });
}
function asFunction(path, filename) {
var argumentsPaths = path.get('arguments');
var string = argumentsPaths[0].evaluate().value;
replace({
path: argumentsPaths[0].parentPath,
string,
filename
});
}
function asJSX(path, filename) {
var children = path.get('children');
var string = children[0].node.expression.value;
if (children[0].node.expression.type === 'TemplateLiteral') {
string = children[0].get('expression').evaluate().value;
}
replace({
path: children[0].parentPath,
string,
filename
});
}
/*
eslint
complexity: ["error", 8]
*/

@@ -1,62 +0,1 @@

{
"name": "babel-plugin-codegen",
"version": "1.2.1",
"description": "Generate code at build-time",
"main": "dist/index.js",
"engines": {
"node": "> 4",
"npm": "> 3"
},
"scripts": {
"add-contributor": "kcd-scripts contributors add",
"build": "kcd-scripts build",
"lint": "kcd-scripts lint",
"test": "kcd-scripts test",
"test:update": "kcd-scripts test --updateSnapshot",
"validate": "kcd-scripts validate",
"precommit": "kcd-scripts precommit"
},
"files": [
"dist",
"macro.js"
],
"keywords": [
"babel-plugin-macros",
"babel-plugin",
"babel",
"code generation"
],
"author": "Kent C. Dodds <kent@doddsfamily.us> (http://kentcdodds.com/)",
"license": "MIT",
"dependencies": {
"babel-core": "^6.26.0",
"babel-plugin-macros": "^2.0.0",
"babel-register": "^6.26.0",
"babel-template": "^6.26.0",
"require-from-string": "^2.0.1"
},
"devDependencies": {
"ast-pretty-print": "^2.0.1",
"babel-plugin-tester": "^5.0.0",
"kcd-scripts": "^0.30.4"
},
"eslintConfig": {
"extends": "./node_modules/kcd-scripts/eslint.js"
},
"eslintIgnore": [
"node_modules",
"coverage",
"dist"
],
"babel": {
"presets": "kcd-scripts/babel"
},
"repository": {
"type": "git",
"url": "https://github.com/kentcdodds/babel-plugin-codegen.git"
},
"bugs": {
"url": "https://github.com/kentcdodds/babel-plugin-codegen/issues"
},
"homepage": "https://github.com/kentcdodds/babel-plugin-codegen#readme"
}
{"name":"babel-plugin-codegen","version":"1.3.0","description":"Generate code at build-time","main":"dist/index.js","engines":{"node":"> 4","npm":"> 3"},"scripts":{"add-contributor":"kcd-scripts contributors add","build":"kcd-scripts build","lint":"kcd-scripts lint","test":"kcd-scripts test","test:update":"kcd-scripts test --updateSnapshot","validate":"kcd-scripts validate","precommit":"kcd-scripts precommit"},"files":["dist","macro.js"],"keywords":["babel-plugin-macros","babel-plugin","babel","code generation"],"author":"Kent C. Dodds <kent@doddsfamily.us> (http://kentcdodds.com/)","license":"MIT","dependencies":{"babel-core":"^6.26.0","babel-plugin-macros":"^2.0.0","babel-register":"^6.26.0","babel-template":"^6.26.0","require-from-string":"^2.0.1"},"devDependencies":{"ast-pretty-print":"^2.0.1","babel-plugin-tester":"^5.0.0","kcd-scripts":"^0.30.4"},"eslintConfig":{"extends":"./node_modules/kcd-scripts/eslint.js"},"eslintIgnore":["node_modules","coverage","dist"],"babel":{"presets":"kcd-scripts/babel"},"repository":{"type":"git","url":"https://github.com/kentcdodds/babel-plugin-codegen.git"},"bugs":{"url":"https://github.com/kentcdodds/babel-plugin-codegen/issues"},"homepage":"https://github.com/kentcdodds/babel-plugin-codegen#readme"}

@@ -15,3 +15,3 @@ <div align="center">

[![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors)
[![All Contributors](https://img.shields.io/badge/all_contributors-2-orange.svg?style=flat-square)](#contributors)
[![PRs Welcome][prs-badge]][prs]

@@ -63,3 +63,4 @@ [![Code of Conduct][coc-badge]][coc]

* [Via Node API](#via-node-api)
* [Use with [`babel-plugin-macros`][babel-plugin-macros]](#use-with-babel-plugin-macrosbabel-plugin-macros)
* [Use with `babel-plugin-macros`](#use-with-babel-plugin-macros)
* [APIs not supported by the macro](#apis-not-supported-by-the-macro)
* [Caveats](#caveats)

@@ -91,11 +92,11 @@ * [Inspiration](#inspiration)

1. All code run by `codegen` is _not_ run in a sandboxed environment
2. All code _must_ run synchronously.
3. All code will be transpiled via `babel-core` directly or `babel-register`
and should follow all of the normal rules for `.babelrc` resolution (the
closest `.babelrc` to the file being run is the one that's used). This means
you can rely on any babel plugins/transforms that you're used to using
elsewhere in your codebase.
4. The code that's generated may or may not be transpiled (babel plugin ordering
is tricky business). **You should generate the code that you wish to ship.**
1. All code run by `codegen` is _not_ run in a sandboxed environment
2. All code _must_ run synchronously.
3. All code will be transpiled via `babel-core` directly or `babel-register`
and should follow all of the normal rules for `.babelrc` resolution (the
closest `.babelrc` to the file being run is the one that's used). This means
you can rely on any babel plugins/transforms that you're used to using
elsewhere in your codebase.
4. The code that's generated may or may not be transpiled (babel plugin ordering
is tricky business). **You should generate the code that you wish to ship.**

@@ -228,3 +229,3 @@ ### Template Tag

## Use with [`babel-plugin-macros`][babel-plugin-macros]
## Use with `babel-plugin-macros`

@@ -247,2 +248,7 @@ Once you've [configured `babel-plugin-macros`](https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/user.md)

### APIs not supported by the macro
* [file comment (`// @codegen`)](#codegen-file-comment--codegen)
* [import comment](#import-comment)
> You could also use [`codegen.macro`][codegen.macro] if you'd prefer to type less 😀

@@ -276,4 +282,4 @@

<!-- prettier-ignore -->
| [<img src="https://avatars.githubusercontent.com/u/1500684?v=3" width="100px;"/><br /><sub><b>Kent C. Dodds</b></sub>](https://kentcdodds.com)<br />[💻](https://github.com/kentcdodds/babel-plugin-codegen/commits?author=kentcdodds "Code") [📖](https://github.com/kentcdodds/babel-plugin-codegen/commits?author=kentcdodds "Documentation") [🚇](#infra-kentcdodds "Infrastructure (Hosting, Build-Tools, etc)") [⚠️](https://github.com/kentcdodds/babel-plugin-codegen/commits?author=kentcdodds "Tests") |
| :---: |
| [<img src="https://avatars.githubusercontent.com/u/1500684?v=3" width="100px;"/><br /><sub><b>Kent C. Dodds</b></sub>](https://kentcdodds.com)<br />[💻](https://github.com/kentcdodds/babel-plugin-codegen/commits?author=kentcdodds "Code") [📖](https://github.com/kentcdodds/babel-plugin-codegen/commits?author=kentcdodds "Documentation") [🚇](#infra-kentcdodds "Infrastructure (Hosting, Build-Tools, etc)") [⚠️](https://github.com/kentcdodds/babel-plugin-codegen/commits?author=kentcdodds "Tests") | [<img src="https://avatars1.githubusercontent.com/u/1958812?v=4" width="100px;"/><br /><sub><b>Michael Rawlings</b></sub>](https://github.com/mlrawlings)<br />[💻](https://github.com/kentcdodds/babel-plugin-codegen/commits?author=mlrawlings "Code") [📖](https://github.com/kentcdodds/babel-plugin-codegen/commits?author=mlrawlings "Documentation") [⚠️](https://github.com/kentcdodds/babel-plugin-codegen/commits?author=mlrawlings "Tests") |
| :---: | :---: |

@@ -280,0 +286,0 @@ <!-- ALL-CONTRIBUTORS-LIST:END -->