Socket
Socket
Sign inDemoInstall

extract-comments

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

extract-comments - npm Package Compare versions

Comparing version 0.10.1 to 1.0.0

lib/code.js

67

index.js
/*!
* extract-comments <https://github.com/jonschlinkert/extract-comments>
*
* Copyright (c) 2014 Jon Schlinkert, contributors.
* Licensed under the MIT license.
* Copyright (c) 2014-2018, Jon Schlinkert.
* Released under the MIT License.
*/

@@ -10,4 +10,3 @@

var extend = require('extend-shallow');
var Comments = require('./lib/comments');
const Extractor = require('./lib/extractor');

@@ -18,18 +17,15 @@ /**

* ```js
* extract(str, options);
* const extract = require('extract-comments');
* console.log(extract(string, options));
* ```
* @param {String} `string`
* @param {Object} `options` Pass `first: true` to return after the first comment is found.
* @return {String}
* @param {Function} `tranformFn` (optional) Tranform function to modify each comment
* @return {Array} Returns an array of comment objects
* @api public
*/
function extract(str, options, fn) {
if (typeof options === 'function') {
fn = options;
options = {};
}
var extracted = new Comments(options, fn);
var res = extracted.extract(str);
return res.comments || [];
function extract(str, options, tranformFn) {
const extractor = new Extractor(options, tranformFn);
return extractor.extract(str);
}

@@ -41,3 +37,3 @@

* ```js
* extract.block(str, options);
* console.log(extract.block(string, options));
* ```

@@ -51,5 +47,5 @@ * @name .block

function block(str, options) {
return extract(str, extend({line: false}, options));
}
extract.block = (str, options) => {
return extract(str, Object.assign({}, options, { line: false }));
};

@@ -60,3 +56,3 @@ /**

* ```js
* extract.line(str, options);
* console.log(extract.line(string, options));
* ```

@@ -70,5 +66,5 @@ * @name .line

function line(str, options) {
return extract(str, extend({block: false}, options));
}
extract.line = (str, options) => {
return extract(str, Object.assign({}, options, { block: false }));
};

@@ -78,2 +74,5 @@ /**

*
* ```js
* console.log(extract.first(string, options));
* ```
* @name .first

@@ -86,25 +85,17 @@ * @param {String} `string`

function first(str) {
return extract(str, {first: true});
}
extract.first = (str, options) => {
return extract(str, Object.assign({}, options, { first: true }));
};
/**
* Expose `extract`
* Expose `Extractor` constructor, to
* allow custom plugins to be registered.
*/
module.exports = extract;
extract.Extractor = Extractor;
/**
* Expose convenience methods
* Expose `extract`
*/
module.exports.block = block;
module.exports.line = line;
module.exports.first = first;
/**
* Expose `Comments` constructor, to
* allow custom plugins to be registered.
*/
module.exports.Comments = Comments;
module.exports = extract;
'use strict';
var utils = require('./utils');
var LineComment = require('./line');

@@ -12,8 +13,7 @@ /**

function BlockComment(str, token) {
this.type = token.type;
this.range = token.range;
this.loc = token.loc;
this.raw = token.value;
this.value = utils.stripStars(this.raw);
class BlockComment extends LineComment {
constructor(str, token) {
super(str, token);
this.value = utils.stripStars(this.raw);
}
}

@@ -20,0 +20,0 @@

@@ -6,3 +6,3 @@ 'use strict';

/**
* Create a new Context object for the given comment.
* Get the code context for the given comment.
*

@@ -13,63 +13,69 @@ * @param {String} `str` string of JavaScript

function Context(str, comment) {
var start = comment.range[1];
var lineno = comment.loc.end.line;
var afterComment = str.slice(start);
var len = afterComment.length, i = 0;
var newlines = 0;
var col = null;
class Context {
constructor(str, comment, nextComment, options) {
this.context = {};
this.value = '';
this.range = [comment.codeStart || 0];
this.context = {};
this.value = '';
this.line = null;
if (options.context === false) {
return;
}
/**
* Loop until we get to a non-whitespace, non-newline character
* If codeContext returns a parsed object, it's used as context,
* otherwise we assume that no code follows the comment.
*/
/**
* Loop until we get to a non-whitespace, non-newline character
* If codeContext returns a parsed object, it's used as context,
* otherwise we assume that no code follows the comment.
*/
while (++i < len) {
var ch = afterComment[i];
const begin = comment.range[1];
const end = nextComment ? nextComment.range[0] : str.length;
if (ch === '/' || ch === '*') {
break;
let after = str.slice(begin, end);
let lineno = comment.loc.end.line;;
let col = 0;
if (after[0] === '\n') {
after = after.slice(1);
} else {
col = comment.loc.end.column;
}
if (ch !== '\n' && ch !== ' ' && ch !== '\t') {
col = start + i;
const lines = after.split('\n');
let rangeStart = begin;
let rangeEnd = begin;
let append = 0;
var line = str.slice(col, str.indexOf('\n', col));
var res = codeContext(line);
if (res) {
this.context = res;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
append += 1;
lineno++;
if (line && !/^\s+/.test(line)) {
this.context = codeContext(line);
this.value = line;
this.line = lineno + newlines + 1;
break;
}
break;
}
if (ch === '\n') {
newlines++;
append += line.length;
}
}
/**
* Create location stats
*/
/**
* Create location object
*/
var end = col !== null
? col + (this.value || '').length
: null;
rangeStart += append;
rangeEnd += append + this.value.length;
this.range = [rangeStart, rangeEnd];
this.loc = {
start: {
line: this.line,
column: col
},
end: {
line: this.line,
column: end
}
};
this.loc = {
start: {
line: lineno,
column: col
},
end: {
line: lineno,
column: col + this.value.length
}
};
}
}

@@ -76,0 +82,0 @@

@@ -10,8 +10,9 @@ 'use strict';

function LineComment(str, token) {
this.type = token.type;
this.range = token.range;
this.loc = token.loc;
this.raw = token.value;
this.value = this.raw.trim();
class LineComment {
constructor(str, token) {
Object.assign(this, token);
this.range = token.range || [token.start, token.end];
this.raw = token.value;
this.value = this.raw.trim();
}
}

@@ -18,0 +19,0 @@

'use strict';
/**
* Utils
*/
var utils = module.exports;
/**
* Create regex for matching JavaScript linting config comments.

@@ -16,3 +10,3 @@ *

utils.toPrefixRegex = function(vendors) {
exports.toPrefixRegex = function(vendors) {
var prefixes = '(' + vendors.join('|') + ')';

@@ -29,3 +23,3 @@ return new RegExp('^' + prefixes);

utils.trimRight = function(str) {
exports.trimRight = function(str) {
return str.replace(/\s+$/, '');

@@ -41,12 +35,6 @@ };

utils.stripStars = function(str) {
exports.stripStars = function(str) {
str = str.replace(/^[ \t]/gm, '');
str = str.replace(/^[ \t]*\*[ \t]?/gm, '');
return utils.trimRight(str);
return exports.trimRight(str);
};
/**
* Expose `utils`
*/
module.exports = utils;
{
"name": "extract-comments",
"description": "Uses esprima to extract line and block comments from a string of JavaScript. Also optionally parses code context (the next line of code after a comment).",
"version": "0.10.1",
"version": "1.0.0",
"homepage": "https://github.com/jonschlinkert/extract-comments",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"contributors": [
"Caleb (https://github.com/cazzer)",
"Jon Schlinkert (http://twitter.com/jonschlinkert)",
"Tomek Wiszniewski (http://tomek.wiszniewski.cc)"
],
"repository": "jonschlinkert/extract-comments",
"bugs": {
"bugs": "https://github.com/jonschlinkert/extract-comments/issues"
"url": "https://github.com/jonschlinkert/extract-comments/issues"
},

@@ -14,26 +19,21 @@ "license": "MIT",

"index.js",
"lib/"
"lib"
],
"main": "index.js",
"engines": {
"node": ">=0.10"
"node": ">=4"
},
"scripts": {
"test": "gulp"
"test": "mocha"
},
"dependencies": {
"define-property": "^0.2.5",
"esprima-extract-comments": "^0.2.1",
"extend-shallow": "^2.0.1",
"parse-code-context": "^0.2.1"
"esprima-extract-comments": "^1.0.1",
"parse-code-context": "^0.2.2"
},
"devDependencies": {
"gulp": "^3.9.0",
"gulp-eslint": "^1.1.1",
"gulp-format-md": "^0.1.4",
"gulp-istanbul": "^0.10.3",
"gulp-mocha": "^2.2.0",
"mocha": "*",
"should": "*",
"time-diff": "^0.1.0"
"babel-extract-comments": "^1.0.0",
"espree-extract-comments": "^0.1.0",
"gulp-format-md": "^1.0.0",
"mocha": "^3.5.3",
"time-diff": "^0.3.1"
},

@@ -57,19 +57,29 @@ "keywords": [

"verb": {
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"related": {
"list": [
"babel-extract-comments",
"code-context",
"espree-extract-comments",
"esprima-extract-comments",
"parse-comments"
],
"description": ""
},
"deps": {
"ignore": [
"fixtures"
]
},
"plugins": [
"gulp-format-md"
]
"reflinks": [
"babel-extract-comments",
"espree-extract-comments",
"esprima",
"esprima-extract-comments"
],
"lint": {
"reflinks": true
}
}
}

@@ -1,5 +0,7 @@

# extract-comments [![NPM version](https://img.shields.io/npm/v/extract-comments.svg)](https://www.npmjs.com/package/extract-comments)
# extract-comments [![NPM version](https://img.shields.io/npm/v/extract-comments.svg?style=flat)](https://www.npmjs.com/package/extract-comments) [![NPM monthly downloads](https://img.shields.io/npm/dm/extract-comments.svg?style=flat)](https://npmjs.org/package/extract-comments) [![NPM total downloads](https://img.shields.io/npm/dt/extract-comments.svg?style=flat)](https://npmjs.org/package/extract-comments) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/extract-comments.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/extract-comments)
> Uses esprima to extract line and block comments from a string of JavaScript. Also optionally parses code context (the next line of code after a comment).
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
## Install

@@ -10,3 +12,3 @@

```sh
$ npm i extract-comments --save
$ npm install --save extract-comments
```

@@ -19,3 +21,3 @@

// pass a string of javascript, CSS, LESS etc
// pass a string of JavaScript
extract(string);

@@ -35,13 +37,54 @@ ```

value: 'this is\na comment',
lines: [ 'this is', 'a comment' ],
loc: { start: { line: 1, pos: 0 }, end: { line: 5, pos: 33 } },
loc: { start: { line: 1, column: 0 }, end: { line: 5, column: 33 } },
code:
{ line: 7,
loc: { start: { line: 7, pos: 36 }, end: { line: 7, pos: 52 } },
loc: { start: { line: 7, column: 36 }, end: { line: 7, column: 52 } },
value: 'var foo = "bar";' }
```
## Extractors
By default, [esprima](http://esprima.org) is used for extracting comments. This can easily be changed by passing a function to `options.extractor`.
**The easy way**
Use a published module, such as:
* [babel-extract-comments](https://github.com/jonschlinkert/babel-extract-comments)
* [esprima-extract-comments](https://github.com/jonschlinkert/esprima-extract-comments)
* [espree-extract-comments](https://github.com/jonschlinkert/espree-extract-comments)
Example:
```js
extract(str, {extractor: require('babel-extract-comments')});
```
If you create a compatible extractor, feel free to do pr [or create an issue](https://github.com/jonschlinkert/extract-comments/issues/new) to add it to the readme!
**Roll your own**
```js
extract(str, {
extractor: function(str) {
// must return an array of tokens with:
// - type: 'Block', 'CommentBlock', 'Line' or 'CommentLine'
// - value: the comment inner string
// - loc: with `start` and `end` line and column
// example:
return [
{
type: 'Block',
{start: { line: 1, column: 0 },
end: { line: 5, column: 33 }},
value: ' this is a comment string '
}
];
}
});
```
## API
### [extract](index.js#L25)
### [extract](index.js#L26)

@@ -54,3 +97,4 @@ Extract comments from the given `string`.

* `options` **{Object}**: Pass `first: true` to return after the first comment is found.
* `returns` **{String}**
* `tranformFn` **{Function}**: (optional) Tranform function to modify each comment
* `returns` **{Array}**: Returns an array of comment objects

@@ -60,6 +104,7 @@ **Example**

```js
extract(str, options);
const extract = require('extract-comments');
console.log(extract(string, options));
```
### [.block](index.js#L48)
### [.block](index.js#L44)

@@ -77,6 +122,6 @@ Extract block comments from the given `string`.

```js
extract.block(str, options);
console.log(extract.block(string, options));
```
### [.line](index.js#L65)
### [.line](index.js#L61)

@@ -94,6 +139,6 @@ Extract line comments from the given `string`.

```js
extract.line(str, options);
console.log(extract.line(string, options));
```
### [.first](index.js#L79)
### [.first](index.js#L78)

@@ -108,58 +153,85 @@ Extract the first comment from the given `string`.

## Related
**Example**
* [code-context](https://www.npmjs.com/package/code-context): Parse a string of javascript to determine the context for functions, variables and comments based… [more](https://www.npmjs.com/package/code-context) | [homepage](https://github.com/jonschlinkert/code-context)
+ [esprima-extract-comments](https://www.npmjs.com/package/esprima-extract-comments): Extract code comments from string or from a glob of files using esprima. | [homepage](https://github.com/jonschlinkert/esprima-extract-comments)
* [parse-comments](https://www.npmjs.com/package/parse-comments): Parse code comments from JavaScript or any language that uses the same format. | [homepage](https://github.com/jonschlinkert/parse-comments)
```js
console.log(extract.first(string, options));
```
## Contributing
## Release history
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/extract-comments/issues/new).
**v0.10.0**
## Tests
* Parsing is now handled by esprima, so only JavaScript can be parsed. I'm working on parsers for other languages and will cross-link those here when they're pushed up.
* Breaking change: since parsing is now done by esprima, on both the line and block comment objects, the `loc.start.pos` and `loc.end.pos` properties have been renamed to `loc.start.column` and `loc.end.column`.
### Run tests
**v0.9.0**
Install dev dependencies:
* Breaking change: `lines` property was removed from `Block` comments, since this can easily be done by splitting `value`
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm i -d && npm test
$ npm install && npm test
```
### Coverage
</details>
As of December 30, 2015:
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
Statements : 100% (133/133)
Branches : 100% (32/32)
Functions : 100% (19/19)
Lines : 100% (132/132)
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
## Release history
</details>
**v0.10.0**
### Related projects
* Parsing is now handled by esprima
* Breaking change: since parsing is now done by esprima, on both the line and block comment objects, the `loc.start.pos` and `loc.end.pos` properties have been renamed to `loc.start.column` and `loc.end.column`.
You might also be interested in these projects:
**v0.9.0**
* [babel-extract-comments](https://www.npmjs.com/package/babel-extract-comments): Uses babel (babylon) to extract JavaScript code comments from a JavaScript string or file. | [homepage](https://github.com/jonschlinkert/babel-extract-comments "Uses babel (babylon) to extract JavaScript code comments from a JavaScript string or file.")
* [code-context](https://www.npmjs.com/package/code-context): Parse a string of javascript to determine the context for functions, variables and comments based… [more](https://github.com/jonschlinkert/code-context) | [homepage](https://github.com/jonschlinkert/code-context "Parse a string of javascript to determine the context for functions, variables and comments based on the code that follows.")
* [espree-extract-comments](https://www.npmjs.com/package/espree-extract-comments): Uses espree to extract JavaScript code comments from a string. Returns an array of comment… [more](https://github.com/jonschlinkert/espree-extract-comments) | [homepage](https://github.com/jonschlinkert/espree-extract-comments "Uses espree to extract JavaScript code comments from a string. Returns an array of comment objects, with line, column, index, comment type and comment string.")
* [esprima-extract-comments](https://www.npmjs.com/package/esprima-extract-comments): Extract code comments from string or from a glob of files using esprima. | [homepage](https://github.com/jonschlinkert/esprima-extract-comments "Extract code comments from string or from a glob of files using esprima.")
* [parse-comments](https://www.npmjs.com/package/parse-comments): Parse code comments from JavaScript or any language that uses the same format. | [homepage](https://github.com/jonschlinkert/parse-comments "Parse code comments from JavaScript or any language that uses the same format.")
* Breaking change: `lines` property was removed from `Block` comments, since this can easily be done by splitting `value`
### Contributors
## Author
| **Commits** | **Contributor** |
| --- | --- |
| 93 | [jonschlinkert](https://github.com/jonschlinkert) |
| 3 | [cazzer](https://github.com/cazzer) |
| 1 | [architectcodes](https://github.com/architectcodes) |
### Author
**Jon Schlinkert**
* [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert)
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
## License
### License
Copyright © 2014-2015 [Jon Schlinkert](https://github.com/jonschlinkert)
Released under the MIT license.
Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb](https://github.com/verbose/verb) on December 30, 2015._
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on February 12, 2018._

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc