Skip to content

Customizable SourceParser #214

Closed
Closed
@fraxken

Description

@fraxken

The goal of the task is to be able to provide a custom SourceParser to the runASTAnalysis function (if not provided it will take the default JsSourceParser for example).

The idea behind that is to allow anyone to extend/add a new Parsing mechanism (to support TypeScript source for example).

In my mind I see two build-in class:

  • SourceParser (with the current constructor code)

constructor(source, options = {}) {
if (typeof source !== "string") {
throw new TypeError("source must be a string");
}
const { removeHTMLComments = false } = options;
this.raw = source;
/**
* if the file start with a shebang then we remove it because meriyah.parseScript fail to parse it.
* @example
* #!/usr/bin/env node
*/
const rawNoShebang = source.charAt(0) === "#" ?
source.slice(source.indexOf("\n") + 1) : source;
this.source = removeHTMLComments ?
this.#removeHTMLComment(rawNoShebang) : rawNoShebang;
}

  • JsSourceParser extending SourceParser (with the current parseScript code). The default parser for JS-X-Ray.

https://github.com/NodeSecure/js-x-ray/blob/master/src/SourceParser.js#L50

If someone want to re-implement his own, it would look like this;

import { SourceParser, runASTAnalysis } from "@nodesecure/js-x-ray";
import { parse } from '@typescript-eslint/typescript-estree';

export class TsSourceParser extends SourceParser {
  parseScript() {
    const ast = parse(this.source, {});

    return ast;
  }
}

const { warnings, dependencies } = runASTAnalysis(
  readFileSync("./file.ts", "utf-8"),
  {
    sourceParser: TsSourceParser
  }
);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions