@babel/types#file TypeScript Examples

The following examples show how to use @babel/types#file. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: parse.ts    From next-core with GNU General Public License v3.0 6 votes vote down vote up
/** For next-core internal or devtools usage only. */
export function parseForAnalysis(
  source: string,
  { typescript, tokens }: AnalysisOptions = {}
): ParseResult<File> {
  try {
    return parse(source, {
      plugins: ["estree", typescript && "typescript"].filter(
        Boolean
      ) as ParserPlugin[],
      strictMode: true,
      attachComment: false,
      // Allow export/import declarations to make analyser handle errors.
      sourceType: "unambiguous",
      tokens,
    });
  } catch (e) {
    // Return no errors if parse failed.
    return null;
  }
}
Example #2
Source File: webpackParser.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
protected parseAst(ast: File, modules: Module[]): void {
    traverse(ast, {
      CallExpression: (nodePath) => {
        const firstArg = nodePath.get('arguments')[0];
        if (isFunctionExpression(nodePath.node.callee) && firstArg?.isArrayExpression()) { // entrypoint
          this.parseArray(ast, firstArg, modules);
        } else if (isMemberExpression(nodePath.node.callee) && isAssignmentExpression(nodePath.node.callee.object) && firstArg?.isArrayExpression()) { // chunked
          const assignment = nodePath.node.callee.object;
          if (isMemberExpression(assignment.left)) {
            let leftPropName = '';
            if (isIdentifier(assignment.left.property)) {
              leftPropName = assignment.left.property.name;
            } else if (isStringLiteral(assignment.left.property)) {
              leftPropName = assignment.left.property.value;
            }
            if (leftPropName.startsWith('webpackJsonp')) {
              const modulesObject = firstArg.get('elements')[1];
              if (modulesObject.isArrayExpression()) {
                this.parseArray(ast, modulesObject, modules);
              } else {
                if (!modulesObject || !modulesObject.isObjectExpression()) throw new Error('Failed assertion');
                this.parseObject(ast, modulesObject, modules);
              }
            }
          }
        }
        nodePath.skip();
      },
    });
  }
Example #3
Source File: webpackParser.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
private parseArray(file: File, ast: NodePath<ArrayExpression>, modules: Module[]): void {
    ast.get('elements').forEach((element, i) => {
      if (!element.isFunctionExpression()) return;
      if (element.node.body.body.length === 0) return;

      const dependencyValues: number[] = [];
      const requireIdentifer = element.node.params[2];
      if (isIdentifier(requireIdentifer)) {
        element.traverse({
          CallExpression: (dependencyPath) => {
            if (!isIdentifier(dependencyPath.node.callee) || !isNumericLiteral(dependencyPath.node.arguments[0])) return;
            if (dependencyPath.scope.bindingIdentifierEquals(dependencyPath.node.callee.name, requireIdentifer)) {
              dependencyValues[dependencyPath.node.arguments[0].value] = dependencyPath.node.arguments[0].value;
            }
          },
        });
      }

      const newModule = new Module(file, element, i, dependencyValues, this.PARAM_MAPPING);
      newModule.calculateFields();
      modules[i] = newModule;
    });
  }
Example #4
Source File: webpackParser.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
private parseObject(file: File, ast: NodePath<ObjectExpression>, modules: Module[]): void {
    ast.get('properties').forEach((property) => {
      if (!property.isObjectProperty() || !isNumericLiteral(property.node.key)) return;

      const element = property.get('value');
      const i = property.node.key.value;
      if (!element.isFunctionExpression()) return;
      if (element.node.body.body.length === 0) return;

      const dependencyValues: number[] = [];
      const requireIdentifer = element.node.params[2];
      if (isIdentifier(requireIdentifer)) {
        element.traverse({
          CallExpression: (dependencyPath) => {
            if (!isIdentifier(dependencyPath.node.callee) || !isNumericLiteral(dependencyPath.node.arguments[0])) return;
            if (dependencyPath.scope.bindingIdentifierEquals(dependencyPath.node.callee.name, requireIdentifer)) {
              dependencyValues[dependencyPath.node.arguments[0].value] = dependencyPath.node.arguments[0].value;
            }
          },
        });
      }

      const newModule = new Module(file, element, i, dependencyValues, this.PARAM_MAPPING);
      newModule.calculateFields();
      modules[i] = newModule;
    });
  }
Example #5
Source File: module.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
constructor(originalFile: File, rootPath: NodePath<FunctionExpression>, moduleId: number, dependencies: number[], paramMappings: ParamMappings) {
    this.originalFile = originalFile;
    this.rootPath = rootPath;
    this.moduleId = moduleId;
    this.dependencies = dependencies;
    this.originalDependencies = dependencies;
    this.paramMappings = paramMappings;

    this.moduleCode = rootPath.node.body;
    this.moduleName = this.moduleId.toString();

    this.globalsParam = this.getFunctionParam(paramMappings.globals);
    this.requireParam = this.getFunctionParam(paramMappings.require);
    this.moduleParam = this.getFunctionParam(paramMappings.module);
    this.exportsParam = this.getFunctionParam(paramMappings.exports);
  }
Example #6
Source File: webpackParser.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
protected parseAst(ast: File, modules: Module[]): void {
    traverse(ast, {
      CallExpression: (nodePath) => {
        const firstArg = nodePath.get('arguments')[0];
        if (isFunctionExpression(nodePath.node.callee) && firstArg?.isArrayExpression()) { // entrypoint
          this.parseArray(ast, firstArg, modules);
        } else if (isMemberExpression(nodePath.node.callee) && isAssignmentExpression(nodePath.node.callee.object) && firstArg?.isArrayExpression()) { // chunked
          const assignment = nodePath.node.callee.object;
          if (isMemberExpression(assignment.left)) {
            let leftPropName = '';
            if (isIdentifier(assignment.left.property)) {
              leftPropName = assignment.left.property.name;
            } else if (isStringLiteral(assignment.left.property)) {
              leftPropName = assignment.left.property.value;
            }
            if (leftPropName.startsWith('webpackJsonp')) {
              const modulesObject = firstArg.get('elements')[1];
              if (modulesObject.isArrayExpression()) {
                this.parseArray(ast, modulesObject, modules);
              } else {
                if (!modulesObject || !modulesObject.isObjectExpression()) throw new Error('Failed assertion');
                this.parseObject(ast, modulesObject, modules);
              }
            }
          }
        }
        nodePath.skip();
      },
    });
  }
Example #7
Source File: webpackParser.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
private parseArray(file: File, ast: NodePath<ArrayExpression>, modules: Module[]): void {
    ast.get('elements').forEach((element, i) => {
      if (!element.isFunctionExpression()) return;
      if (element.node.body.body.length === 0) return;

      const dependencyValues: number[] = [];
      const requireIdentifer = element.node.params[2];
      if (isIdentifier(requireIdentifer)) {
        element.traverse({
          CallExpression: (dependencyPath) => {
            if (!isIdentifier(dependencyPath.node.callee) || !isNumericLiteral(dependencyPath.node.arguments[0])) return;
            if (dependencyPath.scope.bindingIdentifierEquals(dependencyPath.node.callee.name, requireIdentifer)) {
              dependencyValues[dependencyPath.node.arguments[0].value] = dependencyPath.node.arguments[0].value;
            }
          },
        });
      }

      const newModule = new Module(file, element, i, dependencyValues, this.PARAM_MAPPING);
      newModule.calculateFields();
      modules[i] = newModule;
    });
  }
Example #8
Source File: webpackParser.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
private parseObject(file: File, ast: NodePath<ObjectExpression>, modules: Module[]): void {
    ast.get('properties').forEach((property) => {
      if (!property.isObjectProperty() || !isNumericLiteral(property.node.key)) return;

      const element = property.get('value');
      const i = property.node.key.value;
      if (!element.isFunctionExpression()) return;
      if (element.node.body.body.length === 0) return;

      const dependencyValues: number[] = [];
      const requireIdentifer = element.node.params[2];
      if (isIdentifier(requireIdentifer)) {
        element.traverse({
          CallExpression: (dependencyPath) => {
            if (!isIdentifier(dependencyPath.node.callee) || !isNumericLiteral(dependencyPath.node.arguments[0])) return;
            if (dependencyPath.scope.bindingIdentifierEquals(dependencyPath.node.callee.name, requireIdentifer)) {
              dependencyValues[dependencyPath.node.arguments[0].value] = dependencyPath.node.arguments[0].value;
            }
          },
        });
      }

      const newModule = new Module(file, element, i, dependencyValues, this.PARAM_MAPPING);
      newModule.calculateFields();
      modules[i] = newModule;
    });
  }
Example #9
Source File: module.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
constructor(originalFile: File, rootPath: NodePath<FunctionExpression>, moduleId: number, dependencies: number[], paramMappings: ParamMappings) {
    this.originalFile = originalFile;
    this.rootPath = rootPath;
    this.moduleId = moduleId;
    this.dependencies = dependencies;
    this.originalDependencies = dependencies;
    this.paramMappings = paramMappings;

    this.moduleCode = rootPath.node.body;
    this.moduleName = this.moduleId.toString();

    this.globalsParam = this.getFunctionParam(paramMappings.globals);
    this.requireParam = this.getFunctionParam(paramMappings.require);
    this.moduleParam = this.getFunctionParam(paramMappings.module);
    this.exportsParam = this.getFunctionParam(paramMappings.exports);
  }
Example #10
Source File: parser.ts    From amplication with Apache License 2.0 5 votes vote down vote up
export function parse(source: string, options?: Overrides): File {
  return recastBabelParser.parser.parse(source, getOptions(options));
}
Example #11
Source File: partial-parser.ts    From amplication with Apache License 2.0 5 votes vote down vote up
export function parse(source: string, options?: Overrides): File {
  return recastBabelParser.parser.parse(source, getOptions(options));
}
Example #12
Source File: module.ts    From react-native-decompiler with GNU Affero General Public License v3.0 5 votes vote down vote up
/** The original file that held this module */
  originalFile: File;
Example #13
Source File: module.ts    From react-native-decompiler with GNU Affero General Public License v3.0 5 votes vote down vote up
/** The original file that held this module */
  originalFile: File;
Example #14
Source File: get-code-from-ast.ts    From prettier-plugin-sort-imports with Apache License 2.0 5 votes vote down vote up
getCodeFromAst = (
    nodes: Statement[],
    originalCode: string,
    interpreter?: InterpreterDirective | null,
) => {
    const allCommentsFromImports = getAllCommentsFromNodes(nodes);

    const nodesToRemoveFromCode = [
        ...nodes,
        ...allCommentsFromImports,
        ...(interpreter ? [interpreter] : []),
    ];

    const codeWithoutImportsAndInterpreter = removeNodesFromOriginalCode(
        originalCode,
        nodesToRemoveFromCode,
    );

    const newAST = file({
        type: 'Program',
        body: nodes,
        directives: [],
        sourceType: 'module',
        interpreter: interpreter,
        sourceFile: '',
        leadingComments: [],
        innerComments: [],
        trailingComments: [],
        start: 0,
        end: 0,
        loc: {
            start: { line: 0, column: 0 },
            end: { line: 0, column: 0 },
        },
    });

    const { code } = generate(newAST);

    return (
        code.replace(
            /"PRETTIER_PLUGIN_SORT_IMPORTS_NEW_LINE";/gi,
            newLineCharacters,
        ) + codeWithoutImportsAndInterpreter.trim()
    );
}
Example #15
Source File: lint.ts    From next-core with GNU General Public License v3.0 4 votes vote down vote up
/** For next-core internal or devtools usage only. */
export function lint(
  source: string | ParseResult<File>,
  { typescript, rules }: LintOptions = {}
): LintError[] {
  const errors: LintError[] = [];
  const file =
    typeof source === "string"
      ? parseForAnalysis(source, { typescript })
      : source;
  if (!file) {
    // Return no errors if parse failed.
    return errors;
  }
  const body = file.program.body;
  const jsNodes: Statement[] = typescript ? [] : body;
  if (typescript) {
    for (const node of body) {
      if (node.type.startsWith("TS")) {
        if (/Enum|Import|Export/.test(node.type)) {
          errors.push({
            type: "SyntaxError",
            message: `Unsupported TypeScript syntax: \`${node.type}\``,
            loc: node.loc,
          });
        }
      } else {
        jsNodes.push(node);
      }
    }
  }
  let func: FunctionDeclaration;
  for (const node of jsNodes) {
    const isFunctionDeclaration = node.type === "FunctionDeclaration";
    if (isFunctionDeclaration && !func) {
      func = node;
    } else {
      errors.push({
        type: "SyntaxError",
        message: isFunctionDeclaration
          ? "Expect a single function declaration"
          : `\`${node.type}\` is not allowed in top level`,
        loc: node.loc,
      });
    }
  }
  if (!func) {
    errors.unshift({
      type: "SyntaxError",
      message: "Function declaration not found",
      loc: {
        start: { line: 1, column: 0 },
        end: { line: 1, column: 0 },
      },
    });
  } else {
    precook(func, {
      hooks: {
        beforeVisit(node) {
          switch (node.type) {
            case "ArrowFunctionExpression":
            case "FunctionDeclaration":
            case "FunctionExpression":
              if (node.async || node.generator) {
                errors.push({
                  type: "SyntaxError",
                  message: `${
                    node.async ? "Async" : "Generator"
                  } function is not allowed`,
                  loc: node.loc,
                });
              }
              break;
            case "Literal":
              if (node.regex) {
                if (node.value === null) {
                  errors.push({
                    type: "SyntaxError",
                    message: "Invalid regular expression",
                    loc: node.loc,
                  });
                } else if (node.regex.flags.includes("u")) {
                  errors.push({
                    type: "SyntaxError",
                    message: "Unsupported unicode flag in regular expression",
                    loc: node.loc,
                  });
                }
              }
              break;
            case "ObjectExpression":
              for (const prop of node.properties) {
                if (prop.type === "Property") {
                  if (prop.kind !== "init") {
                    errors.push({
                      type: "SyntaxError",
                      message: "Unsupported object getter/setter property",
                      loc: prop.loc,
                    });
                  } else if (
                    !prop.computed &&
                    prop.key.type === "Identifier" &&
                    prop.key.name === "__proto__"
                  ) {
                    errors.push({
                      type: "TypeError",
                      message: "Setting '__proto__' property is not allowed",
                      loc: prop.key.loc,
                    });
                  }
                }
              }
              break;
            case "VariableDeclaration":
              if (node.kind === "var" && rules?.noVar) {
                errors.push({
                  type: "SyntaxError",
                  message:
                    "Var declaration is not recommended, use `let` or `const` instead",
                  loc: {
                    start: node.loc.start,
                    end: {
                      line: node.loc.end.line,
                      // Only decorate the "var".
                      column: node.loc.start.column + 3,
                    },
                  },
                });
              }
              break;
          }
        },
        beforeVisitGlobal(node) {
          if (node.name === "arguments") {
            errors.push({
              type: "SyntaxError",
              message: "Use the rest parameters instead of 'arguments'",
              loc: node.loc,
            });
          }
        },
        beforeVisitUnknown(node) {
          errors.push({
            type: "SyntaxError",
            message: `Unsupported syntax: \`${node.type}\``,
            loc: node.loc,
          });
          return true;
        },
      },
    });
  }
  return errors;
}