export let tests = () => { const dependencies = [ requireModule({ identifier: 'ava', module: `ava` }), requireModule({ identifier: 'plugin', module: `./plugin` }), requireModule({ identifier: 'suites', module: `./tests` }) ]; const tmpl = template(` suites.forEach(function (suite) { suite.forEach(function (test) { ava(test.fixture, function (t) { t.same(plugin(test.fixture), test.valid); }); }); }); `); let program = t.program([ tmpl() ]); return warning() + dependencies.join('') + generate(program).code; };
export let test = opts => { let tests = (prop, valid) => { return value => { return t.objectExpression([ t.objectProperty( t.identifier('fixture'), t.stringLiteral(`${prop}: ${value}`) ), t.objectProperty( t.identifier('valid'), t.identifier(valid ? 'true' : 'false') ) ]); }; }; let program = t.program([ template('module.exports = EXPORTS;')({ EXPORTS: t.arrayExpression(flatten(opts.properties.map(prop => { const valid = opts.valid.map(tests(prop, true)); const invalid = opts.invalid.map(tests(prop, false)); return valid.concat(invalid); }))) }) ]); return warning() + generate(program).code; };
StringLiteral: function(path) { if (!path.node.macro) return; try { var buildArgs = {}, args = path.node.args; for (var i = 0; i < args.length; i++) { buildArgs["$" + i] = args[i]; } var tmp = path.node.value // Replace spread aguments like in `$0($1...)` .replace(/\$(\d+)\.\.\./, function (m, i) { var rep = [], j = parseInt(i); for (; j < args.length; j++) { rep.push("$" + j); } return rep.join(","); }) // Replace optional arguments like in `$0[$1]{{=$2}}` .replace(/\{\{([^\}]*\$(\d+).*?)\}\}/g, function (_, g1, g2) { var i = parseInt(g2); return i < args.length ? g1 : ""; }); var buildMacro = template(tmp); path.replaceWithMultiple(buildMacro(buildArgs)); } catch (err) { console.log("BABEL ERROR: Failed to parse macro: " + path.node.value); process.exit(1); } }
const buildImport = (args) => (template(` ( typeof window === 'undefined' ? new (require('next/dynamic').SameLoopPromise)((resolve, reject) => { eval('require.ensure = function (deps, callback) { callback(require) }') require.ensure([], (require) => { let m = require(SOURCE) m.__webpackChunkName = '${args.name}.js' resolve(m); }, 'chunks/${args.name}.js'); }) : new (require('next/dynamic').SameLoopPromise)((resolve, reject) => { const weakId = require.resolveWeak(SOURCE) try { const weakModule = __webpack_require__(weakId) return resolve(weakModule) } catch (err) {} require.ensure([], (require) => { try { let m = require(SOURCE) resolve(m) } catch(error) { reject(error) } }, 'chunks/${args.name}.js'); }) ) `))
exit: function (path) { if (path.BABEL_PLUGIN_ADD_RETURN_EXPORTS) { return; } path.pushContainer('body', [babelTemplate("if (typeof exports === 'object' && exports && exports.__esModule) return exports;")()]); path.BABEL_PLUGIN_ADD_RETURN_EXPORTS = true; }
export let requireModule = opts => { const requireTemplate = template('var IDENTIFIER = require(MODULE);'); let ast = requireTemplate({ IDENTIFIER: t.identifier(opts.identifier), MODULE: t.stringLiteral(opts.module) }); return generate(ast).code + '\n'; };
['length', 'integer', 'percentage', 'number', 'time'].forEach(type => { if (!opts[type]) { return; } const camel = 'is' + type[0].toUpperCase() + type.slice(1, type.length); conditions.push(template(`!${camel}(node.value)`)().expression); dependencies.push(requireModule({ identifier: camel, module: `../../validators/${camel}` })); });
export let exportModules = exported => { const exportTemplate = template('module.exports = EXPORTS'); let ast = exportTemplate({ EXPORTS: t.arrayExpression(exported.map((value, index) => { if (index === exported.length - 1) { return t.identifier(`\n ${value}\n`); } return t.identifier(`\n ${value}`); })) }); return generate(ast).code + '\n'; };
/** * @module babel-plugin-transform-string-raw * @returns {babelPlugin} unknown */ export default () => ({ visitor: { CallExpression(path) { if (path.get('callee').matchesPattern('String.raw')) { path.replaceWith(template(`${defineName}($0)`)(path.node.arguments)); } }, Program: { exit(path) { for (const node of path.node.body) { const declaration = (node.declarations || [])[0] || {}; const name = declaration.id && declaration.id.name; if (name === defineName) { return; } } const topNodes = []; topNodes.push(template(`var ${defineName} = String.raw || ${_stringRaw}`)()); path.unshiftContainer('body', topNodes); }, }, }, });
VariableDeclarator: (p) => { const { id, init } = p.node; if (t.isIdentifier(id) && !id.name.startsWith(constant_1.LOOP_STATE)) { const newId = scope.generateDeclaredUidIdentifier('$' + id.name); refIds.forEach((refId) => { if (refId.name === variableName && !variableName.startsWith('_$')) { refIds.delete(refId); } }); variableName = newId.name; refIds.add(t.identifier(variableName)); blockStatement.scope.rename(id.name, newId.name); p.parentPath.replaceWith(template('ID = INIT;')({ ID: newId, INIT: init })); } }
const deep_equal = (babel) => { const t = babel.types; const buildRequire = template(deep_equal_code); let counter = 0; const modifiedBinaryExpr = () => { const exp = t.binaryExpression("===", nodes[counter].left, nodes[counter].right); counter++; exp.isClean = true; return exp; } const ast = buildRequire({ BINARYEXPR: modifiedBinaryExpr(), }); return { visitor: { BinaryExpression(path) { if(path.node.isClean) return; // return if this expression is not satisfied // deep-equal does not perform operation on literals const returnExp = path.node.operator=== '===' && t.isIdentifier(path.node.right) && t.isIdentifier(path.node.left); if(!returnExp) return; /* (() => { * //deep_equal_fn code here * * return deep_equal_fn(node.left, node.right); * })(); */ path.replaceWith( t.callExpression( t.arrowFunctionExpression([], t.blockStatement( [ast,t.returnStatement(t.callExpression(t.identifier('deep_equal_fn'),[path.node.left,path.node.right]))] ) ) ,[])); } } } };
it("should convert string", function () { const code = ` /** * @param {number} param - this is a param. * @param {string} b - this is a param. * @param {string[]} [c] - this is a param. */ function myFunc(param, b, c){} `; const AST = parse(code); const MyVisitor = { FunctionDeclaration(path) { const node = path.node; if (node.leadingComments && node.leadingComments.length === 1) { const comment = node.leadingComments[0]; if (comment.type === 'CommentBlock') { const assertions = CommentConverter.toAsserts(comment).join("\n"); const buildAssert = template(assertions)(); path.get("body").unshiftContainer("body", buildAssert); } } } }; traverse(AST, { enter(path) { path.traverse(MyVisitor); } }); const result = generate(AST, {}, code); assert.equal(result.code, ` /** * @param {number} param - this is a param. * @param {string} b - this is a param. * @param {string[]} [c] - this is a param. */ function myFunc(param, b, c) { console.assert(typeof param === "number", 'Invalid JSDoc: typeof param === "number"'); console.assert(typeof b === "string", 'Invalid JSDoc: typeof b === "string"'); }`); });
function buildFullPathThisPropsRef(id, memberIds, path) { const scopePath = findDeclarationScope(path, id); const binding = scopePath.scope.getOwnBinding(id.name); if (binding) { const bindingPath = binding.path; if (bindingPath.isVariableDeclarator()) { const dclId = bindingPath.get('id'); const dclInit = bindingPath.get('init'); let dclInitIds = []; if (dclInit.isMemberExpression()) { dclInitIds = getIdsFromMemberProps(dclInit.node); if (dclId.isIdentifier()) { memberIds.shift(); } if (dclInitIds[0] === 'this' && dclInitIds[1] === 'props') { return template(dclInitIds.concat(memberIds).join('.'))().expression; } } } } }
export let plugin = () => { const dependencies = [ requireModule({ identifier: 'validators', module: `./properties/` }), requireModule({ identifier: 'valueParser', module: `postcss-value-parser` }) ]; const tmpl = template(` module.exports = function isValid (cssString) { var parts = cssString.split(':').map(function (value) { return value.trim(); }); var parsed = valueParser(parts[1]); if (parsed.nodes.length === 1 && ~GLOBALS.indexOf(parsed.nodes[0].value)) { return true; } var invalid = validators.some(function (validator) { if (!~validator.properties.indexOf(parts[0])) { return; } return !validator(parsed); }); return !invalid; } `); let program = t.program([ tmpl({ GLOBALS: t.arrayExpression(globals.map(toStringLiteral)) }) ]); return warning() + dependencies.join('') + generate(program).code; };
'use strict' // babel-plugin-__coverage__ // // This is my first Babel plugin, and I wrote it during the night. // Therefore, be prepared to see a lot of copypasta and wtf code. import template from 'babel-template' import nameFunction from 'babel-helper-function-name' import { realpathSync } from 'fs' const coverageTemplate = template(` var FILE_COVERAGE function COVER () { if (!FILE_COVERAGE) FILE_COVERAGE = GET_INITIAL_FILE_COVERAGE() return FILE_COVERAGE } function GET_INITIAL_FILE_COVERAGE () { var global = (new Function('return this'))() var coverage = global['__coverage__'] || (global['__coverage__'] = { }) return coverage[PATH] || (coverage[PATH] = global['JSON'].parse(INITIAL)) } `) // // Takes a relative path and returns a real path. // Assumes the path name is relative to working directory. // function getRealpath (n) { try { return realpathSync(n) || n } catch (e) { return n
/* eslint indent: 0 */ import template from "babel-template"; import * as t from "babel-types"; let buildRest = template(` for (var LEN = ARGUMENTS.length, ARRAY = Array(ARRAY_LEN), KEY = START; KEY < LEN; KEY++) { ARRAY[ARRAY_KEY] = ARGUMENTS[KEY]; } `); let loadRest = template(` ARGUMENTS.length <= INDEX ? undefined : ARGUMENTS[INDEX] `); let memberExpressionOptimisationVisitor = { Scope(path, state) { // check if this scope has a local binding that will shadow the rest parameter if (!path.scope.bindingIdentifierEquals(state.name, state.outerBinding)) { path.skip(); } }, Flow(path) { // don't touch reference in type annotations path.skip(); },
ExportDefaultDeclaration: function (path) { topNodes = [] topNodes.push(babelTemplate("return exports['default']")()) path.insertAfter(topNodes); }
/* eslint max-len: 0 */ import { basename, extname } from "path"; import template from "babel-template"; let buildPrerequisiteAssignment = template(` GLOBAL_REFERENCE = GLOBAL_REFERENCE || {} `); let buildGlobalExport = template(` var mod = { exports: {} }; factory(BROWSER_ARGUMENTS); PREREQUISITE_ASSIGNMENTS GLOBAL_TO_ASSIGN = mod.exports; `); let buildWrapper = template(` (function (global, factory) { if (typeof define === "function" && define.amd) { define(MODULE_NAME, AMD_ARGUMENTS, factory); } else if (typeof exports !== "undefined") { factory(COMMON_ARGUMENTS); } else { GLOBAL_EXPORT } })(this, FUNC); `); export default function ({ types: t }) { function isValidDefine(path) { if (!path.isExpressionStatement()) return;
import template from "babel-template"; let buildDefine = template(` define(MODULE_NAME, [SOURCES], FACTORY); `); let buildFactory = template(` (function (PARAMS) { BODY; RETURN; }) `); export default function ({ types: t }) { function isValidRequireCall(path) { if (!path.isCallExpression()) return false; if (!path.get("callee").isIdentifier({ name: "require" })) return false; if (path.scope.getBinding("require")) return false; let args = path.get("arguments"); if (args.length !== 1) return false; let arg = args[0]; if (!arg.isStringLiteral()) return false; return true; } function isDefineCall(path) { return path.isCallExpression() && path.get("callee").isIdentifier({ name: "define" });
// template params: // // - NAME component name // - EXPORT component export value import template from 'babel-template'; export default template(` const EXPORT_NAME = EXPORT_VALUE; EXPORT_NAME.name = EXPORT_NAME.name || EXTERNAL_LABEL_NAME; EXPORT_NAME.style = EXPORT_NAME.style || EXTERNAL_STYLE_NAME; EXPORT_NAME.template = EXPORT_NAME.template || EXTERNAL_TEMPLATE_NAME; ko.components.register(EXPORT_NAME); `);
* Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file. * @private */ import template from 'babel-template'; import { booleanLiteral, numericLiteral, stringLiteral } from 'babel-types'; const pattern = /^\s*?=>( async)?\s*/; const tpl = template(` (function() { var assert = require('assert'); assert.equal(result, ASSERTION); })(); `); /** * Indicates whether the specifed value defines a literal assertion * @param {string} value * @returns {Boolean} */ export function test(value) { return pattern.test(value); } /** * Builds a literal assertion * @param {string} value
import getFunctionArity from "babel-helper-get-function-arity"; import callDelegate from "babel-helper-call-delegate"; import template from "babel-template"; import * as t from "babel-types"; const buildDefaultParam = template(` let VARIABLE_NAME = ARGUMENTS.length > ARGUMENT_KEY && ARGUMENTS[ARGUMENT_KEY] !== undefined ? ARGUMENTS[ARGUMENT_KEY] : DEFAULT_VALUE; `); const buildCutOff = template(` let $0 = $1[$2]; `); function hasDefaults(node) { for (const param of (node.params: Array<Object>)) { if (!t.isIdentifier(param)) return true; } return false; } function isSafeBinding(scope, node) { if (!scope.hasOwnBinding(node.name)) return true; const { kind } = scope.getOwnBinding(node.name); return kind === "param" || kind === "local"; } const iifeVisitor = {
import { util } from 'babel-core' import template from 'babel-template' import nameFunction from 'babel-helper-function-name' import { realpathSync } from 'fs' import { createHash } from 'crypto' const coverageTemplate = template(` var FILE_COVERAGE function COVER () { if (!FILE_COVERAGE) FILE_COVERAGE = GET_INITIAL_FILE_COVERAGE() return FILE_COVERAGE } function GET_INITIAL_FILE_COVERAGE () { var path = PATH, hash = HASH var global = (new Function('return this'))() var coverage = global['__coverage__'] || (global['__coverage__'] = { }) if (coverage[path] && coverage[path].hash === hash) return coverage[path] var coverageData = global['JSON'].parse(INITIAL) coverageData.hash = hash return coverage[path] = coverageData } COVER () `) // // Takes a relative path and returns a real path. // Assumes the path name is relative to working directory. // function getRealpath (n) { try {
[t.arrayExpression(data.options.map(makePropType))] ); } else if (method === 'void') { node = dontSetTemplate().expression; } else if (method === 'instanceOf') { node = t.callExpression( t.memberExpression(node, t.identifier('instanceOf')), [t.identifier(data.of)] ) } else { $debug('Unknown node ' + JSON.stringify(data, null, 2)); throw new Error(`${PLUGIN_NAME} processing error: This is an internal error that should never happen. ` + `Report it immediately with the source file and babel config. Data: ${data}`); } if (isRequired && data.isRequired && method !== 'void') { node = t.memberExpression(node, t.identifier('isRequired')); } return node; } const dontSetTemplate = template(` (props, propName, componentName) => { if(props[propName] != null) return new Error(\`Invalid prop \\\`\${propName}\\\` of value \\\`\${value}\\\` passed to \\\`\${componentName\}\\\`. Expected undefined or null.\`); } `);
import getFunctionArity from "babel-helper-get-function-arity"; import callDelegate from "babel-helper-call-delegate"; import template from "babel-template"; import * as t from "babel-types"; let buildDefaultParam = template(` let VARIABLE_NAME = ARGUMENTS.length <= ARGUMENT_KEY || ARGUMENTS[ARGUMENT_KEY] === undefined ? DEFAULT_VALUE : ARGUMENTS[ARGUMENT_KEY]; `); let buildDefaultParamAssign = template(` if (VARIABLE_NAME === undefined) VARIABLE_NAME = DEFAULT_VALUE; `); let buildCutOff = template(` let $0 = $1[$2]; `); function hasDefaults(node) { for (let param of (node.params: Array<Object>)) { if (!t.isIdentifier(param)) return true; } return false; } let iifeVisitor = { ReferencedIdentifier(path, state) { let name = path.node.name;
import template from "babel-template"; const build = template(` for( let TARGET = ARR, INDEX = 0, VALUE, L = TARGET.length; ( VALUE = TARGET[INDEX] ), INDEX < L; INDEX++ ) BODY; `); export default function forEach({path, types: t}) { let [arrArg, callbackArg] = path.node.arguments; let [valueArg, indexArg] = callbackArg.params; const callbackBody = callbackArg.body.body; /* super dirty hach which get rids of return when using arrow function without body */ if(callbackBody.length === 1 && !callbackBody[0].loc && callbackBody[0].type === 'ReturnStatement') { callbackBody[0] = callbackBody[0].argument; } return { build, nodes: { BODY: callbackArg.body,
/* @flow */ import type { NodePath } from "babel-traverse"; import nameFunction from "babel-helper-function-name"; import template from "babel-template"; import * as t from "babel-types"; let buildWrapper = template(` (function () { var ref = FUNCTION; return function (PARAMS) { return ref.apply(this, arguments); }; }) `); let awaitVisitor = { Function(path) { path.skip(); }, AwaitExpression({ node }) { node.type = "YieldExpression"; } }; function classMethod(path: NodePath, callId: Object) { let node = path.node; let body = node.body; node.async = false;
'use strict' const template = require('babel-template') const t = require('babel-types') const isNilWrapper = template( '(function (val) { return val === null || typeof val === \'undefined\' })' ) function addIsNilHelper() { // Modified from https://github.com/babel/babel/blob/master/packages/babel-core/src/transformation/file/index.js#L280 const name = 'isNilWrapper' const declar = this.declarations[name] if (declar) { return declar } if (!this.usedHelpers[name]) { this.metadata.usedHelpers.push(name) this.usedHelpers[name] = true } const generator = this.get('helperGenerator') const runtime = this.get('helpersNamespace') if (generator) { const res = generator(name) if (res) { return res
// babel plugin to transform es6 modules into brackets compatible modules // based on https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-es2015-modules-amd/src/index.js var template = require('babel-template'); // wrap everything in iife to avoid leaking globals var iifeDeclaration = template('(function () { \'use strict\'; BODY; }())'); // if the file is loaded within brackets (define is present), use it to declare module // otherwise (define is not present in brackets node domains) execute immediately var checkForDefineDeclaration = template('if (typeof define !== \'undefined\') { define(bracketsModule); } else { bracketsModule(require, exports, module); }'); // this is the template for module declaration var bracketsModuleDeclaration = template('function bracketsModule(require, exports, module) { BODY; }'); module.exports = function (_babel) { // var t = babel.types; return { inherits: require('babel-plugin-transform-es2015-modules-commonjs'), visitor: { Program: { exit: function exit(path) { if (path.bracketsModuleFormatterRan) { return; } path.bracketsModuleFormatterRan = true; var node = path.node; // create the iife and put original body into bracketsModule function var iife = iifeDeclaration({
let replace = blockScoping.run(); if (replace) path.replaceWith(replace); }, "BlockStatement|Program"(path, file) { if (!t.isLoop(path.parent)) { let blockScoping = new BlockScoping(null, path, path.parent, path.scope, file); blockScoping.run(); } } } }; } let buildRetCheck = template(` if (typeof RETURN === "object") return RETURN.v; `); function isBlockScoped(node) { if (!t.isVariableDeclaration(node)) return false; if (node[t.BLOCK_SCOPED_SYMBOL]) return true; if (node.kind !== "let" && node.kind !== "const") return false; return true; } function convertBlockScopedToVar(path, parent, scope, moveBindingsToParent = false) { const { node } = path; // https://github.com/babel/babel/issues/255 if (!t.isFor(parent)) { for (let i = 0; i < node.declarations.length; i++) { let declar = node.declarations[i];