Skip to content

Commit

Permalink
🎉Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
richardDobron committed Oct 17, 2021
0 parents commit 8ded61b
Show file tree
Hide file tree
Showing 12 changed files with 4,196 additions and 0 deletions.
20 changes: 20 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module.exports = {
root: true,
env: {
commonjs: true,
es6: true,
node: true,
},
extends: "eslint:recommended",
globals: {
Atomics: "readonly",
SharedArrayBuffer: "readonly",
},
parserOptions: {
ecmaVersion: 2018,
},
plugins: ["prettier"],
rules: {
"prettier/prettier": "warn",
},
};
25 changes: 25 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: tests

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
build:
runs-on: ubuntu-latest

strategy:
matrix:
node-version: [10.x, 12.x, 14.x]

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: yarn --no-progress --frozen-lockfile
- run: yarn lint
- run: yarn test
61 changes: 61 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# next.js build output
.next
2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*
!index.js
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Richard Dobroň

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
99 changes: 99 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# babel-plugin-transform-private-class-members ![](https://github.com/richardDobron/babel-plugin-transform-private-class-members/workflows/tests/badge.svg) [![npm](https://img.shields.io/npm/v/babel-plugin-transform-private-class-members.svg)](https://www.npmjs.com/package/babel-plugin-transform-private-class-members)

Mangle JavaScript private class members.

## Installation

```
$ npm install babel-plugin-transform-private-class-members
```

## Usage

### Via `.babelrc` (Recommended)

**.babelrc**

```json
{
"plugins": ["babel-plugin-transform-private-class-members"]
}
```

### Via CLI

```sh
$ babel --plugins babel-plugin-transform-private-class-members script.js
```

### Via Node API

```javascript
require("babel-core").transform("code", {
plugins: ["babel-plugin-transform-private-class-members"]
});
```

## Example

Input file:

```js
class Rectangle {
result = null;

constructor(height, width) {
this._height = height;
this._width = width;
}

area() {
if (this.result === null) {
this.result = this._calcArea();
}

return this.result;
}

_calcArea() {
return this._height * this._width;
}
}
```

Output:

```js
class Rectangle {
result = null;

constructor(height, width) {
this.$1 = height;
this.$2 = width;
}

area() {
if (this.result === null) {
this.result = this.$3();
}

return this.result;
}

$3() {
return this.$1 * this.$2;
}
}
```

## Options

| Option | Description | Default |
| ----------- | --------------------------------------------------------- | ------------------------------------------- |
| blacklist | A RegEx defining which members to ignore | *[ /^_super.*/, /^__.*/, /^_$/, /^[^_].*/ ] |
| memoize | Keep mangle position and keys for another transform | *false* |
| onlyClass | Replace only private class members and properties | *true* |

## License

This plugin is licensed under the MIT license. See [LICENSE](./LICENSE).
157 changes: 157 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
const defaultBlacklist = [
/^_super.*/, // prefix _super
/^_extend.*/, // prefix _extend
/^__.*/, // prefix __
/^_$/, // underscore
/^[^_].*/, // properties without underscore
];

function escapeRegExp(pattern) {
if (Object.prototype.toString.call(pattern) === "[object RegExp]") {
return pattern.source.replace(/\//g, "/");
} else if (typeof pattern === "string") {
// eslint-disable-next-line
const escaped = pattern.replace(/[\-\[\]\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

return escaped.replace(/\//g, "\\" + "/");
} else {
throw new Error("Unexpected blacklist pattern: " + pattern);
}
}

function blacklist(additionalBlacklist) {
return new RegExp(
"(" +
(additionalBlacklist || [])
.concat(defaultBlacklist)
.map(escapeRegExp)
.join("|") +
")$"
);
}

module.exports = function ({ types: t }, options = {}) {
let privateId = 1;

const blacklistRegex = blacklist(options.blacklist),
memoize = options.memoize || false,
onlyClassMembers =
options.onlyClassMembers === undefined ? true : options.onlyClassMembers,
nameMap = new Map();

function createPrivateName(name) {
let newName = nameMap.get(name);
if (!newName) {
newName = "$" + privateId++;
nameMap.set(name, newName);
}

return newName;
}

function isPrototypeMethod(assignment) {
const { left } = assignment;

if (
left &&
t.isMemberExpression(left) &&
t.isMemberExpression(left.object) &&
left.object.property.name === "prototype"
) {
return left.object.object.name;
}

return null;
}

const replaceClassPropertyOrMethod = {
exit(path) {
const { node } = path;

if (
onlyClassMembers &&
!t.isClassProperty(node) &&
!t.isClassMethod(node) &&
!t.isIdentifier(node.key)
) {
return;
}

if (t.isIdentifier(node.key) && node.computed) {
return;
}

const name = node.key.name || node.key.value;

if (blacklistRegex.test(name)) {
return;
}

const newName = createPrivateName(name),
newNode = t.cloneNode(node, false);

if (t.isIdentifier(node.key) && t.isValidIdentifier(newName)) {
newNode.key = t.identifier(newName);
} else {
newNode.key = t.stringLiteral(newName);
}

path.replaceWith(newNode);
path.skip();
},
};

return {
name: "transform-private-class-members",
visitor: {
Property: replaceClassPropertyOrMethod,
Method: replaceClassPropertyOrMethod,
MemberExpression: {
exit(path) {
const { node } = path;

if (
onlyClassMembers &&
!t.isThisExpression(node.object) &&
!isPrototypeMethod(path.parent)
) {
return;
}

if (!t.isIdentifier(node.property) || node.computed) {
return;
}

const { name } = node.property;

if (blacklistRegex.test(name)) {
return;
}

const newName = createPrivateName(name);

let newNode;

if (t.isValidIdentifier(newName)) {
newNode = t.memberExpression(node.object, t.identifier(newName));
} else {
newNode = t.memberExpression(
node.object,
t.stringLiteral(newName),
true
);
}

path.replaceWith(newNode);
path.skip();
},
},
},
post: () => {
if (!memoize) {
nameMap.clear();
privateId = 1;
}
},
};
};
Loading

0 comments on commit 8ded61b

Please sign in to comment.