Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
_createCaptureScopeAccessFunction(referentializationScope: ReferentializationScope): void | BabelNodeStatement {
// One switch case for one scope.
const cases = [];
const serializedScopes = this._getReferentializationState(referentializationScope).serializedScopes;
type InitializationCase = {|
scopeIDs: Array,
value: BabelNodeExpression,
|};
const initializationCases: Map = new Map();
for (const scopeBinding of serializedScopes.values()) {
if (scopeBinding.initializationValues.length === 0) continue;
const expr = t.arrayExpression((scopeBinding.initializationValues: any));
const key = generate(expr, {}, "").code;
if (!initializationCases.has(key)) {
initializationCases.set(key, {
scopeIDs: [scopeBinding.id],
value: expr,
});
} else {
const ic = initializationCases.get(key);
invariant(ic);
ic.scopeIDs.push(scopeBinding.id);
}
}
if (initializationCases.size === 0) return undefined;
const body = [];
const selectorParam = t.identifier("__selector");
const captured = t.identifier("__captured");
if (
ast.some(
stmt => !(isExpressionStatement(stmt) || isEmptyStatement(stmt)),
)
) {
throw Error('Unhandled');
}
// ast is (ExpressionStatement|EmptyStatement)[]
updted = [
listToLogical((ast as any) as (ExpressionStatement | EmptyStatement)[]),
].filter(v => v !== undefined) as Statement[];
}
onChange({
'@class': 'Script',
language: 'JavaScript',
content: generate(program(updted)).code,
});
}
const fstStmt = ast[0];
export function getModuleMetadata(element: IRElement): ModuleDependency {
let properties;
// Note that we only collect properties and not attributes (such as 'class', 'data-*')
if (element.props) {
properties = {};
for (const [name, value] of Object.entries(element.props)) {
let returnedType;
let returnedValue;
if (value.type === IRAttributeType.Expression) {
returnedType = 'expression';
const expression = value.value as TemplateExpression;
if (babelTypes.isMemberExpression(expression)) {
returnedValue = generate(expression).code;
} else {
returnedValue = (expression as TemplateIdentifier).name;
}
} else {
returnedType = 'literal';
returnedValue = value.value;
}
properties[name] = {
type: returnedType,
value: returnedValue,
};
}
}
return {
moduleName: kebabcaseToCamelcase(element.component),
function extractPropertyFromExpressionStatement(
statement: babel.ExpressionStatement,
document: JavaScriptDocument): ScannedProperty|null {
let name;
let astNode;
let defaultValue;
if (babel.isAssignmentExpression(statement.expression)) {
// statements like:
// /** @public The foo. */
// this.foo = baz;
name = getPropertyNameOnThisExpression(statement.expression.left);
astNode = statement.expression.left;
defaultValue = generate(statement.expression.right).code;
} else if (babel.isMemberExpression(statement.expression)) {
// statements like:
// /** @public The foo. */
// this.foo;
name = getPropertyNameOnThisExpression(statement.expression);
astNode = statement;
} else {
return null;
}
if (name === undefined) {
return null;
}
const annotation = getJSDocAnnotationForNode(statement);
if (!annotation) {
const nopt = require('nopt');
const opts = {
compact: Boolean
};
const parsed = nopt(opts, null, process.argv, 2);
const compact = parsed.compact;
const generateOptions = {
compact
};
for (let i = 1; i < 15; i += 1) {
const n = Math.pow(2, i);
const prog = toProgram(n);
const start = new Date().getTime();
const codeMap = generate(prog, generateOptions, '');
const end = new Date().getTime();
if (i == 1) {
console.log('Sample prog:', codeMap.code);
}
console.log('Items:', n, ', time:', end - start);
}
it("Works with substititions and simple viewport units", () => {
const ast = babel.parse(`
const Test = styled(Button)\`
color: \${red};
top: 10vw;
opacity: \${something};
\`;
`);
babel.traverse(ast, {
TaggedTemplateExpression(path: any) {
const { tag, quasi: body } = path.node;
const element = tag.arguments[0];
buildElement(babel, path, element, body, { jsx: true });
}
});
const { code } = generate(ast);
expect(code).toMatchInlineSnapshot(`
"import React from \\"react\\";
import useWindowDimensions from \\"cssta/runtime/useWindowDimensions\\";
const Test = React.forwardRef((props, ref) => {
const {
width: windowWidth,
height: windowHeight
} = useWindowDimensions();
const baseStyle = {
color: String(red).trim(),
top: Number(windowWidth * 0.1),
opacity: Number(something)
};
const style = props.style != null ? [baseStyle, props.style] : baseStyle;
return <button style="{style}">;
});"</button>
function instrument(inputFilename: string, outputFilename: string) {
let code = fs.readFileSync(inputFilename, "utf8");
let ast = parse(code, { inputFilename, sourceType: "script" });
traverseFast(ast, function(node) {
if (node.type === "BlockStatement") {
if (node.loc) ((node: any): BabelNodeBlockStatement).body.unshift(createLogStatement(node.loc));
}
return false;
});
code = generate(ast, {}, "").code;
if (!outputFilename) outputFilename = inputFilename + "-instrumented.js";
fs.writeFileSync(outputFilename, code);
console.log(`Instrumented source code written to ${outputFilename}.`);
}
const processModule = await context.resolveSimple('process', file.filePath)
const ast = template.ast`
${file.imports.map(i => `require(${JSON.stringify(i)})`).join('\n')}
var style = document.createElement('style')
style.type = 'text/css'
if (require(${JSON.stringify(processModule)}).env.NODE_ENV === "development" && module.hot && module.hot.dispose) {
module.hot.dispose(function() {
style.remove()
})
}
style.textContent = ${JSON.stringify(css)}
document.head.appendChild(style)
module.exports = ${JSON.stringify(options.scoped ? randomId : null)}
`
const generated = generate(t.program(ast))
file.addImport(processModule)
file.sourceContents = Buffer.from(css, 'utf8')
return {
contents: generated.code,
sourceMap: null,
}
},
defaultOptions: {
export const classDeclarationConverter = ({ node }) => {
return `class ${generate(node.id).code} ${
node.superClass ? ` extends ${generate(node.superClass).code}` : ''
}`;
};
generateCode(AST) {
if (this.type === ParserTypes.Esprima) {
return generate(AST, {
comment: this.options.comment
});
} else if (this.type === ParserTypes.Babylon) {
return babelGenerate(AST);
}
}