Debian Codegraph @

esniff/README.md

raw
1 [![Build status][build-image]][build-url]
2 [![Tests coverage][cov-image]][cov-url]
3 [![npm version][npm-image]][npm-url]
4
5 # esniff
6
7 ## Low footprint JavaScript source code parser
8
9 Low footprint, fast source code parser, which allows you to find all code fragment occurrences with respect to all syntax rules that cannot be handled with plain regular expression search.
10
11 It aims at use cases where we don't need full AST tree, but instead we're interested in finding usages of given function, property etc. in syntactically valid code.
12
13 ### Installation
14
15 #### npm
16
17 $ npm install esniff
18
19 ### Usage
20
21 Using main module you can configure sophisticated parser on your own. However, first, **see preprared [API utilities](#API) that may already address use cases you have**.
22
23 #### esniff(code, executor)
24
25 - `code` - Code to parse
26 - `executor` - A function to be executed immediately by the constructor, It receives an `emitter` parameter.
27
28 `emitter` emits following events:
29
30 - `trigger:<char>` - When char is a code character approached in code, that is not a whitespaces, is not in a middle of identificator, is not part of a comment, string, template string or regular expression.
31
32 Emitter passes to listener and `accessor` object, which provides access to current parser state and allows to manipulate parsing process. `accessor` exposes following methods:
33
34 - `skipCodePart(codePart)` - Skips forward through input _codePart_ assuming parser index points start of given part. Returns true if given `codePart` was found and index and skipped
35 - `skipIdentifier` - Skips approached identifier (can be function name or property name), returns `{ name, start, end }` meta object
36 - `skipWhitespace` - Skips any whitespace and comments founds at current parsing index
37 - `collectScope` - If at current index `(` character is found, it registers given paranthesis scope for registrations (it's content will be returned as one of the results after finished parsing)
38 - `stop` - Stops parsing process
39 - `index` - Returns currently parsed index
40 - `previousToken` - Previous non-whitespace character
41 - `scopeDepth` - Current scope depth
42 - `shouldCollectComments` - Whether data about code comments should be collected in the result
43
44 ##### Example
45
46 Parse all `require(..)` calls:
47
48 ```javascript
49 var esniff = require("esniff");
50
51 var parseRequires = function (code) {
52 return esniff(code, function (emitter) {
53 emitter.on("trigger:r", function (accessor) {
54 if (accessor.previousToken === ".") return;
55 if (!accessor.skipCodePart("require")) return;
56 accessor.skipWhitespace();
57 accessor.collectScope();
58 });
59 });
60 };
61
62 console.log(parseRequires("var x = require('foo/bar')"));
63 [{ type: "scope", point: 17, column: 17, line: 1, raw: "'foo/bar'" }];
64 ```
65
66 #### Predefined utils for common use cases
67
68 #### accessedProperties(objName) _(esniff/accessed-properties)_
69
70 Returns function which allows us to find all accessed property names on given object name
71
72 ```javascript
73 var findProperties = require("esniff/accessed-properties");
74 var findContextProperties = findProperties("this");
75
76 var result = findContextProperties(
77 "var foo = \"0\"; this.bar = foo; this.someMethod(); otherFunction()"
78 );
79 console.log(result); // [ { name: 'bar', start: 20, end: 23 }, { name: 'someMethod', start: 36, end: 46 } ]
80 ```
81
82 #### function(name[, options]) _(esniff/function)_
83
84 Returns function which allows us to find all occurrences of given function (or method) being invoked
85
86 Through options we can restrict cases which we're after:
87
88 - `asProperty` (default: `false`), on true will allow `x.name()` when we search for `name` calls
89 - `asPlain` (default: `true`), on true it allows plain calls e.g. `name()` when we search for `name`. Should be set to `false` if we're strictly about method calls.
90
91 Setting both `asProperty` and `asPlain` to false, will always produce empty result
92
93 ```javascript
94 var findRequires = require("esniff/function")("require");
95
96 findRequires("var x = require('foo/bar')");
97 // [{ point: 17, column: 17, line: 1, raw: '\'foo/bar\'' }]
98 ```
99
100 #### resolveArguments(code[, limit]) _(esniff/resolve-arguments)_
101
102 Resolves expressions separated with commas, with additional `limit` you can specify after which number of arguments resolver should stop
103
104 ```javascript
105 var resolveArgs = require("esniff/resolve-arguments");
106
107 var result = resolveArgs("'raz', 'dwa', ['raz', 'dwa'], 'trzy'", 3);
108
109 console.log(result); // ['"raz"', ' "dwa"', ' [\'raz\', \'dwa\']']
110 ```
111
112 ### Limitations
113
114 - _esniff_ assumes code that you pass is syntactically correct, it won't inform you about any syntax errors and may produce unexpected and nonsense results when such code is used.
115 - There's single case of syntactically correct code, which will make _esniff_ produce incorrect results, it's division made directly on object literal (e.g. `x = { foo: 'bar' } / 14`, esniff in that case will assume that `/` starts regular expression). Still there's not known use case where such code may make any sense, and many popular JS source code parsers share very same vulnerability.
116
117 ## Tests
118
119 $ npm test
120
121 ## Security contact information
122
123 To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.
124
125 [build-image]: https://github.com/medikoo/esniff/workflows/Integrate/badge.svg
126 [build-url]: https://github.com/medikoo/esniff/actions?query=workflow%3AIntegrate
127 [cov-image]: https://img.shields.io/codecov/c/github/medikoo/esniff.svg
128 [cov-url]: https://codecov.io/gh/medikoo/esniff
129 [npm-image]: https://img.shields.io/npm/v/esniff.svg
130 [npm-url]: https://www.npmjs.com/package/esniff