Compare commits

...

448 Commits

Author SHA1 Message Date
Sebastian McKenzie
9c79290bb2 v4.7.5 2015-03-10 13:20:20 +11:00
Sebastian McKenzie
cfdf6b7385 add 4.7.5 changelog 2015-03-10 13:12:19 +11:00
Sebastian McKenzie
907e0e0f86 drop support for node 0.10 to save travis some unnecessary cycles <3 2015-03-10 13:11:06 +11:00
Sebastian McKenzie
f3bd9cbcb8 use a different helper if a class contains class methods to avoid non-enumerability and delegation to es6.properties.computed transformer - fixes #984, closes #986 2015-03-10 13:04:02 +11:00
Sebastian McKenzie
3bd14f9e07 add babel version to register hook cache key 2015-03-10 13:03:22 +11:00
Sebastian McKenzie
102b4b3d1e remove redundant break wrapping in for-of - fixes #985 2015-03-10 12:14:21 +11:00
Sebastian McKenzie
6564f1ff76 4.7.4 2015-03-10 06:13:37 +11:00
Sebastian McKenzie
58d7a5e069 more versatile scope pushing 2015-03-10 06:13:32 +11:00
Sebastian McKenzie
f5db53cebe remove core-js library from babel-runtime 2015-03-10 06:13:16 +11:00
Sebastian McKenzie
2da010fcae clean up #982 2015-03-10 06:11:55 +11:00
Sebastian McKenzie
52b99bdf93 Merge pull request #982 from tricknotes/error-stack
Ignore assignment to Error#stack if it is readonly property
2015-03-10 06:09:03 +11:00
Ryunosuke SATO
9d7e953451 Ignore assignment to Error#stack if it is readonly property
`Error#stack` may be an readonly property in some environments
such as PhantomJS 1.9.2 and Safari 7.0.
2015-03-10 04:05:53 +09:00
Sebastian McKenzie
b1252b865b v4.7.4 2015-03-10 03:29:47 +11:00
Sebastian McKenzie
068b1341d9 fix erroneous whitespace 2015-03-10 03:28:36 +11:00
Sebastian McKenzie
20eb143915 remove Number from the list of valid runtime constructors - fixes #981 2015-03-10 03:27:13 +11:00
Sebastian McKenzie
1302a86bf2 scope -> scopable class alias key 2015-03-10 03:22:55 +11:00
Sebastian McKenzie
b7831f1d7b prepend mocha command with node 2015-03-10 03:15:31 +11:00
Sebastian McKenzie
e46cabb21f remove code coverage from travis make task 2015-03-10 03:12:50 +11:00
Sebastian McKenzie
fff06a047e Revert "delegate node path removal to after call"
This reverts commit 5e0236d9a7.
2015-03-10 02:50:43 +11:00
Sebastian McKenzie
6b0320fc83 disable test262 tests by default 2015-03-10 02:34:35 +11:00
Sebastian McKenzie
5dde63fa0a more elaborate tests for #980 2015-03-10 02:13:00 +11:00
Sebastian McKenzie
672118149a hoist all directives - fixes #980 2015-03-10 01:53:51 +11:00
Sebastian McKenzie
5e0236d9a7 delegate node path removal to after call 2015-03-10 01:44:58 +11:00
Sebastian McKenzie
5101664e7d update 4.7.4 changelog 2015-03-10 01:44:44 +11:00
Sebastian McKenzie
2d684a06d3 update changelog version to 4.7.4 2015-03-10 01:23:24 +11:00
Sebastian McKenzie
e31bad8f42 add 4.7.3 changelog 2015-03-10 01:17:14 +11:00
Sebastian McKenzie
644b4373fc rewrite named function expressions in async function transformers - fixes #979 2015-03-10 01:16:38 +11:00
Sebastian McKenzie
62f37c1e62 fix util.booleanify 2015-03-10 01:10:58 +11:00
Sebastian McKenzie
fc0e89463b use flow types for annotations - goodbye JSDoc! 2015-03-10 00:35:52 +11:00
Sebastian McKenzie
56b6a795a4 remove path.refreshScope until i'm more confident on it's functionality so it doesn't break peopls stuff 2015-03-09 23:09:22 +11:00
Sebastian McKenzie
17b34a2959 dynamic scope tracking, toot toot - fixes #957 2015-03-09 22:07:05 +11:00
Sebastian McKenzie
c4da0253c5 move flattenable keys to types 2015-03-09 16:55:00 +11:00
Sebastian McKenzie
5f2df40f6d consistent whitespace in patch 2015-03-09 16:54:50 +11:00
Sebastian McKenzie
7d20a9b882 add traversal path todos 2015-03-09 16:54:41 +11:00
Sebastian McKenzie
ee0ac9f149 use spread in messages 2015-03-09 16:54:30 +11:00
Sebastian McKenzie
c5d3f42d8a alias core-js/library in babel-runtime - closes #965 2015-03-09 16:54:19 +11:00
Sebastian McKenzie
d162919a53 update symols transformer name 2015-03-09 03:39:30 +11:00
Sebastian McKenzie
d1f712344d add istanbul auxiliary comment task to makefile 2015-03-09 03:38:39 +11:00
Sebastian McKenzie
e985912b54 add Binary node cleanup 2015-03-09 03:38:27 +11:00
Sebastian McKenzie
97a21e4a34 update spec.typeofSymbol references to es6.symbols 2015-03-09 03:38:13 +11:00
Sebastian McKenzie
d8fb7812f7 more utility.removeConsole tests 2015-03-09 03:37:42 +11:00
Sebastian McKenzie
bfe63f5885 rename spec.typeofSymbol transformer to es6.symbols 2015-03-09 03:37:26 +11:00
Sebastian McKenzie
44ca6873a3 add super to contextVariables 2015-03-09 03:37:05 +11:00
Sebastian McKenzie
2f66ea7338 4.7.3 2015-03-08 04:33:50 +11:00
Sebastian McKenzie
70967cf53c v4.7.3 2015-03-08 04:32:46 +11:00
Sebastian McKenzie
dc117a74ae both -> inline - thanks @dkieks 2015-03-08 04:29:48 +11:00
Sebastian McKenzie
b0f32a822d pass file.addImport a name instead of an identifier 2015-03-08 04:10:53 +11:00
Sebastian McKenzie
fd99ea1749 Merge branch 'master' of github.com:babel/babel 2015-03-08 04:05:44 +11:00
Sebastian McKenzie
572129542d fallback to current parentPath if none was provided 2015-03-08 04:04:48 +11:00
Sebastian McKenzie
6f53980bfc move runtime helpers to separate modules - babel/ember-cli-babel#24 2015-03-08 04:04:40 +11:00
Sebastian McKenzie
348af1990d Merge pull request #972 from neVERberleRfellerER/node-external-helpers-tests
add tests for babel-external-helpers
2015-03-08 03:50:28 +11:00
Ondrej Kraus
bd5f350728 add tests for babel-external-helpers 2015-03-07 17:46:40 +01:00
Sebastian McKenzie
958fa282f4 4.7.2 2015-03-08 03:12:09 +11:00
Sebastian McKenzie
31e6b18346 v4.7.2 2015-03-08 03:09:43 +11:00
Sebastian McKenzie
d17ac92a3f fix changelog version 2015-03-08 03:06:46 +11:00
Sebastian McKenzie
188bcb70f7 add 4.7.1 changelog 2015-03-08 03:03:17 +11:00
Sebastian McKenzie
b8bd11a0e7 fix incorrect builder reference 2015-03-08 03:02:19 +11:00
Sebastian McKenzie
45bc74efe7 use a lookup table instead of an if - #945 2015-03-08 02:57:37 +11:00
Sebastian McKenzie
7eb169a894 Merge pull request #945 from neVERberleRfellerER/helper-globals-fix
Add choice of output format to babel-external-helpers
2015-03-08 02:56:30 +11:00
Sebastian McKenzie
eed4f312d8 add sourceMap both option - closes #966 2015-03-08 02:54:23 +11:00
Sebastian McKenzie
44e4dc970f more es6 2015-03-08 02:52:23 +11:00
Sebastian McKenzie
5d32432e67 split up export variable declarations - fixes #939, fixes #964 2015-03-08 02:52:10 +11:00
Sebastian McKenzie
9c9af6dbbd add utility.removeClass tests and move parentPath setting to setContext - fixes #967 2015-03-08 02:49:58 +11:00
Sebastian McKenzie
70cd650e10 remove dead t.isFalsyExpression and ignore private properties in t.cloneDeep - fixes #962 2015-03-08 02:45:14 +11:00
Sebastian McKenzie
c7bb00d58d ignore case breaks - fixes #963 2015-03-07 17:41:56 +11:00
Ondrej Kraus
623be068c4 add unsupportedOutputType to messages.js 2015-03-07 01:53:34 +01:00
Ondrej Kraus
71f5c9791d replace switch with if-else chain 2015-03-07 01:50:50 +01:00
Ondrej Kraus
3e6e86d073 order template keys by length 2015-03-07 01:50:49 +01:00
Ondrej Kraus
a0fb398ca2 add possibility to select format of external helpers 2015-03-07 01:50:49 +01:00
Ondrej Kraus
71b9f19e6a change to normal UMD (fixes bug with leaking variable in AMD mode) 2015-03-07 01:50:48 +01:00
Ondrej Kraus
c45ce58f0c stop assigning to global in generated helpers code 2015-03-07 01:50:48 +01:00
Sebastian McKenzie
d32f587e3c expose dynamicImports when es6.modules is blacklisted babel/ember-cli-babel#24 2015-03-07 03:31:24 +11:00
Sebastian McKenzie
9e1874ba89 4.7.1 2015-03-07 03:31:05 +11:00
Sebastian McKenzie
35fdc5c5d8 v4.7.1 2015-03-07 02:52:17 +11:00
Sebastian McKenzie
a4035fc257 use convert-source-map package - closes #960 2015-03-07 02:46:15 +11:00
Sebastian McKenzie
42e3dc7a70 inherit all options from input source map 2015-03-07 02:28:33 +11:00
Sebastian McKenzie
cdccf24515 4.7.0 2015-03-07 02:04:58 +11:00
Sebastian McKenzie
c8cd5c108b v4.7.0 2015-03-07 01:59:02 +11:00
Sebastian McKenzie
2b95b876e1 return only constructor if class was a named class with only a constructor/no constructor 2015-03-07 01:50:34 +11:00
Sebastian McKenzie
f801772fc2 add inputSourceMap option - fixes #827, related babel/babel-loader#35 2015-03-07 01:50:07 +11:00
Sebastian McKenzie
8ad678e5bc make it illegal to have a rest on a setter 2015-03-07 01:32:03 +11:00
Sebastian McKenzie
35c49dbef7 merge validation transformers 2015-03-07 01:25:44 +11:00
Sebastian McKenzie
119314df74 update traceur 2015-03-07 01:25:37 +11:00
Sebastian McKenzie
51e336b037 class declarations also have a lexical self binding 2015-03-07 01:25:18 +11:00
Sebastian McKenzie
7d446807a9 remove rogue console.log 2015-03-06 23:40:30 +11:00
Sebastian McKenzie
8afdeaf557 replicate module environment in babel-node -e - closes #695, fixes #592 2015-03-06 23:39:49 +11:00
Sebastian McKenzie
4df50954a2 use instance indexOf instead of lodash - #951 2015-03-06 23:31:11 +11:00
Sebastian McKenzie
70b6317865 Merge pull request #951 from neVERberleRfellerER/babel-node-args-fix
add possiblity of passing colliding user arguments by separating them with --
2015-03-06 23:30:31 +11:00
Sebastian McKenzie
5ebdc44297 remove babel-runtime version check to node api 2015-03-06 23:20:48 +11:00
Sebastian McKenzie
a4659fd239 add reference checks for module specifiers - fixes #956 2015-03-06 23:19:26 +11:00
Sebastian McKenzie
19bfa4a35b add debug message for travis... 2015-03-06 23:15:20 +11:00
Sebastian McKenzie
f7fff7d35e add alternate to list of STATEMENT_OR_BLOCK_KEYS - fixes #955 2015-03-06 23:13:03 +11:00
Sebastian McKenzie
130e0ebe6b better classes, more spec compliant and nicer output - fixes #952 2015-03-06 23:08:10 +11:00
Sebastian McKenzie
69c836fc8d Merge branch 'master' of github.com:babel/babel 2015-03-06 02:27:15 +11:00
Sebastian McKenzie
f62a3ef394 further develop ast paths that represent a single location in the ast as an abstraction around a node-parent relationship 2015-03-06 02:26:04 +11:00
Sebastian McKenzie
7a6e568940 clean up classes output 2015-03-06 02:25:24 +11:00
Sebastian McKenzie
65998c3437 add error message for incompatible babel-runtime versions 2015-03-06 02:23:30 +11:00
Ondrej Kraus
160de340b0 add possiblity of passing user arguments by separating them with --
Now, when user arguments have names colliding with node arguments,
they can be separated by -- and will be parsed correctly.
2015-03-05 14:35:53 +01:00
Sebastian McKenzie
76ca40f698 Merge pull request #944 from sindresorhus/modularize-tofastproperties
modularize `util.toFastProperties()`
2015-03-05 01:10:26 +11:00
Sindre Sorhus
01ed824b5c modularize util.toFastProperties()
https://github.com/sindresorhus/to-fast-properties
2015-03-04 21:02:36 +08:00
Sebastian McKenzie
6b0dbc4486 bump regenerator-babel 2015-03-04 23:29:37 +11:00
Sebastian McKenzie
2648268f30 add contextVariables to scope 2015-03-04 22:54:00 +11:00
Sebastian McKenzie
8cf5bf7037 add filename arg to resolveModuleSource option 2015-03-04 22:53:50 +11:00
Sebastian McKenzie
60961bc3ff bump ast-types - fixes #930 2015-03-04 22:53:38 +11:00
Sebastian McKenzie
df16bc17e7 clean up formatting of system module formatter 2015-03-04 22:52:44 +11:00
Sebastian McKenzie
5337ab5a08 statically bind super references in object expressions - fixes #943 2015-03-04 22:52:07 +11:00
Sebastian McKenzie
2eaeebcce4 inherit from class constructor block statement - fixes #937 2015-03-03 23:38:11 +11:00
Sebastian McKenzie
ad71010144 4.6.6 2015-03-03 22:44:44 +11:00
Sebastian McKenzie
864169c1eb v4.6.6 2015-03-03 22:43:06 +11:00
Sebastian McKenzie
930d7f9aa6 add 4.6.6 changelog 2015-03-03 22:38:20 +11:00
Sebastian McKenzie
ed40ec03d1 more es6, template literals and modules 2015-03-03 22:31:49 +11:00
Sebastian McKenzie
73062ae240 take into consideration non-identifier nodes in es6.blockScopingTDZ transformer, also turn default and parameters into lets instead of vars - fixes #929 2015-03-03 22:30:52 +11:00
Sebastian McKenzie
bafa3e0d4c add missing is - fixes #931 - thanks @neVERberleRfellerER 2015-03-03 10:38:18 +11:00
Sebastian McKenzie
f3d2b2bb81 Merge branch 'master' of github.com:babel/babel 2015-03-03 09:49:35 +11:00
Sebastian McKenzie
a74b67d4eb Merge pull request #932 from hzoo/more-es6
More es6
2015-03-03 09:49:29 +11:00
Sebastian McKenzie
625416862f remove no es6 syntax line from contributing.md 2015-03-03 09:49:20 +11:00
Sebastian McKenzie
8dda8838ba check for body existence before length in dead code elimination transformer - fixes #931 2015-03-03 09:37:52 +11:00
Henry Zhu
96d3a25213 use more es6 concise methods 2015-03-02 10:34:30 -05:00
Sebastian McKenzie
727208f376 4.6.5 2015-03-02 22:55:36 +11:00
Sebastian McKenzie
1b046a6ecb v4.6.5 2015-03-02 22:54:35 +11:00
Sebastian McKenzie
3b8ed0d401 add 4.6.5 changelog 2015-03-02 22:51:21 +11:00
Sebastian McKenzie
d4c98d7738 add transformer aliases 2015-03-02 22:47:00 +11:00
Sebastian McKenzie
4e44af819f fix rogue strict reference 2015-03-02 22:45:21 +11:00
Sebastian McKenzie
a65acd73ca fix rogue useStrict transformer references 2015-03-02 22:41:55 +11:00
Sebastian McKenzie
b7cb2bcb7b rename useStrict transformer to strict 2015-03-02 22:37:51 +11:00
Sebastian McKenzie
5ac4dc0541 don't evaluate ArrayExpressions 2015-03-02 17:16:10 +11:00
Sebastian McKenzie
99ddd02b0a change Function export to avoid messing with istanbul 2015-03-02 15:38:43 +11:00
Sebastian McKenzie
19cfee14fd 4.6.4 2015-03-02 15:38:31 +11:00
Sebastian McKenzie
fea487bf91 v4.6.4 2015-03-02 15:34:10 +11:00
Sebastian McKenzie
ff2cbd5a2e Merge branch 'master' of github.com:babel/babel 2015-03-02 15:30:30 +11:00
Sebastian McKenzie
12e01f9e71 remove optional property on function params - fixes #927 2015-03-02 15:30:05 +11:00
Sebastian McKenzie
f62436909d Merge pull request #923 from mathiasbynens/patch-4
Explicitly update the regexpu dependency to v1.1.2
2015-03-02 11:32:27 +11:00
Mathias Bynens
e42c1adeb6 Explicitly update the regexpu dependency to v1.1.2 2015-03-01 18:50:17 +01:00
Sebastian McKenzie
e30dbbab94 properly replace labels in spec for of transformer - fixes #913, closes #914 2015-03-02 01:41:13 +11:00
Sebastian McKenzie
e3daa28e60 rename minification tests to utility 2015-03-02 01:28:34 +11:00
Sebastian McKenzie
9e5d94126c add base type tests 2015-03-02 01:28:17 +11:00
Sebastian McKenzie
95798bee0b add t.valueToNode 2015-03-02 01:28:10 +11:00
Sebastian McKenzie
63f25ab038 check parent for variable collisions when remapping closurified block scopes - fixes #915, closes #922 2015-03-02 01:27:58 +11:00
Sebastian McKenzie
27a8f2d2ea rename broke property to confident in t.evaluate 2015-03-01 18:16:27 +11:00
Sebastian McKenzie
78434bb404 add t.evaluate method 2015-03-01 17:01:46 +11:00
Sebastian McKenzie
82833a8901 update 4.6.3 changelog 2015-03-01 13:45:09 +11:00
Sebastian McKenzie
93d5288d71 4.6.3 2015-03-01 11:05:33 +11:00
Sebastian McKenzie
5d3074b460 v4.6.3 2015-03-01 11:03:55 +11:00
Sebastian McKenzie
a57475abc9 better rest param member expression deopt 2015-03-01 11:01:06 +11:00
Sebastian McKenzie
09e68d8d46 v4.6.2 2015-03-01 10:12:43 +11:00
Sebastian McKenzie
ee850c3aeb merge fix for #917 with #918 2015-03-01 10:09:03 +11:00
Sebastian McKenzie
ff5a149cec Merge branch 'master' of github.com:babel/babel
# Conflicts:
#	src/babel/transformation/transformers/es6/parameters.rest.js
2015-03-01 10:04:52 +11:00
Sebastian McKenzie
957118fb41 delay rest optimisation, deopt on unoptimisable references - fixes #918 2015-03-01 10:04:16 +11:00
Sebastian McKenzie
e7ad0a9741 Merge pull request #919 from neVERberleRfellerER/rest-args-optimization-fix
fix rest optimization in arrow functions
2015-03-01 09:38:00 +11:00
Ondrej Kraus
24f4b041c7 fix rest optimization in arrow functions and add advanced test 2015-02-28 23:28:21 +01:00
Sebastian McKenzie
4c77d04b56 more es6 modules 2015-03-01 01:01:51 +11:00
Sebastian McKenzie
e945f0d10f add support for outputting flow types - fixes #665 2015-03-01 00:32:36 +11:00
Sebastian McKenzie
fb04b2561f copy over files in watch mode 2015-02-28 21:39:40 +11:00
Sebastian McKenzie
a4f8b41507 4.6.1 2015-02-28 11:56:46 +11:00
Sebastian McKenzie
1fb6018e9c v4.6.1 2015-02-28 11:55:47 +11:00
Sebastian McKenzie
bca233d22c add 4.6.1 changelog 2015-02-28 11:52:21 +11:00
Sebastian McKenzie
c78703e194 blacklist regenerator from templates directory - fixes #912 2015-02-28 11:47:18 +11:00
Sebastian McKenzie
43fdbe3d6c fix whitespace 2015-02-28 11:31:43 +11:00
Sebastian McKenzie
8650ca7d55 properly expose util - fixes #52 2015-02-28 11:24:51 +11:00
Sebastian McKenzie
3a0c226a34 upgrade babel 2015-02-28 00:31:35 +11:00
Sebastian McKenzie
73e8bdd048 update 4.6.0 changelog 2015-02-28 00:31:28 +11:00
Sebastian McKenzie
e7c52a734e 4.6.0 2015-02-27 21:14:20 +11:00
Sebastian McKenzie
5a81b02569 v4.6.0 2015-02-27 21:09:17 +11:00
Sebastian McKenzie
999baf2888 fix regex tests 2015-02-27 21:01:13 +11:00
Sebastian McKenzie
70b25e8942 add sticky regex desugaring #904 2015-02-27 20:51:48 +11:00
Sebastian McKenzie
2ddbd4eecc fix es for of break test expected 2015-02-27 20:33:42 +11:00
Sebastian McKenzie
7520807df3 move eslint out of the core into a separate plugin 2015-02-27 16:30:53 +11:00
Sebastian McKenzie
974b71bcc3 flesh out eslint support 2015-02-27 16:11:47 +11:00
Sebastian McKenzie
0aee3c06ec add noCheckAst option to enforce newline test 2015-02-27 15:45:09 +11:00
Sebastian McKenzie
a4382580fc ignore user whitespace when splitting up module declaration - fixes #906 2015-02-27 15:25:13 +11:00
Sebastian McKenzie
166b2eda87 remove rogue export in node api 2015-02-27 15:08:01 +11:00
Sebastian McKenzie
83c23d266f add eslint with an acorn-babel compatibility layer, yay! coming soon to a production release near you 2015-02-27 13:17:22 +11:00
Sebastian McKenzie
a9db70b60d close iterators on abrupt completion - google/traceur-compiler#1773 #838 2015-02-27 11:44:13 +11:00
Sebastian McKenzie
5d90c442cb fix es6 rest parameters transformer comment 2015-02-26 23:25:48 +11:00
Sebastian McKenzie
32606ddb93 remove linting mention from contributing guide 2015-02-26 22:34:54 +11:00
Sebastian McKenzie
330f6910c6 remove unnecessary exception catch and process.exit - fixes #901 2015-02-26 22:33:36 +11:00
Sebastian McKenzie
4ca8a0e6e2 bump browserify 2015-02-26 21:41:15 +11:00
Sebastian McKenzie
f097ddeac3 bump source-map dependency 2015-02-26 21:39:54 +11:00
Sebastian McKenzie
1eb53dd13a add try-catch to bin watching compilation - fixes #901 2015-02-26 21:28:54 +11:00
Sebastian McKenzie
75b5f32e7a make js-tokens version fixed - explanation in #900 2015-02-26 21:15:54 +11:00
Sebastian McKenzie
f753cf4845 Merge pull request #900 from lydell/js-tokens-1.0
Upgrade to js-tokens@1.0.0
2015-02-26 21:13:55 +11:00
Simon Lydell
9a569f64da Upgrade to js-tokens@1.0.0
This commit also adds syntax highlighting for `null`, `false` and `true`.
2015-02-26 11:11:23 +01:00
Sebastian McKenzie
8efeae80af remove export function Function 2015-02-26 20:39:30 +11:00
Sebastian McKenzie
4df9cf6c05 add missing transform import and change babel import to a wildcard 2015-02-26 20:26:08 +11:00
Sebastian McKenzie
7729cb4b68 start using es6 modules 2015-02-26 20:13:00 +11:00
Sebastian McKenzie
307ffcd107 correctly get old extension handler in registerExtension 2015-02-26 16:00:06 +11:00
Sebastian McKenzie
751557aef1 make #889 more efficient and flexible 2015-02-26 15:24:12 +11:00
Sebastian McKenzie
3f146b54ff Merge branch 'master' of github.com:6to5/6to5 2015-02-26 15:04:21 +11:00
Sebastian McKenzie
19a173c622 Merge pull request #899 from xjamundx/patch-1
feat(6to5/register) don't override uncaughtException handler
2015-02-26 15:04:02 +11:00
Sebastian McKenzie
89bcb307a2 Merge pull request #889 from neVERberleRfellerER/rest-args-optimization-v2
Add rest parameters optimization
2015-02-26 15:03:51 +11:00
Sebastian McKenzie
ded1e02da7 move buildHelpers require down a slot 2015-02-26 13:06:15 +11:00
Sebastian McKenzie
564ba67190 4.5.5 2015-02-26 13:06:08 +11:00
Sebastian McKenzie
00c964ed19 v4.5.5 2015-02-26 13:03:02 +11:00
Sebastian McKenzie
3ab88e02c7 delete from require.extensions when old extension handler is undefined 2015-02-26 12:58:01 +11:00
Sebastian McKenzie
bb2fc830eb use some spreads 2015-02-26 12:57:43 +11:00
Sebastian McKenzie
c6a542fd1d finish remaining class conversion 2015-02-26 12:34:05 +11:00
Sebastian McKenzie
553eb2d45e more classes! 2015-02-26 12:19:28 +11:00
Ondrej Kraus
b5f3c3f4cc stop traversal when it is clear that optimization is impossible 2015-02-26 02:05:26 +01:00
Ondrej Kraus
5d83638583 set literal MemberExpression as computed in rest array destructuring 2015-02-26 01:22:00 +01:00
Sebastian McKenzie
f7186980e5 add external helpers test #898 2015-02-26 09:24:28 +11:00
Sebastian McKenzie
0eaaaa503e 4.5.4 2015-02-26 09:24:10 +11:00
Sebastian McKenzie
51dff364db v4.5.4 2015-02-26 09:21:55 +11:00
Sebastian McKenzie
dc6129eb6a fix helper whitelist in build script 2015-02-26 09:19:49 +11:00
Sebastian McKenzie
5b84b9c867 4.5.3 2015-02-26 09:11:15 +11:00
Sebastian McKenzie
04c3027f4d v4.5.3 2015-02-26 09:10:31 +11:00
Sebastian McKenzie
95e2345b19 move whitelist detection up to before the key is camelcased 2015-02-26 09:08:39 +11:00
Sebastian McKenzie
eafb02be31 4.5.2 2015-02-26 09:08:17 +11:00
Sebastian McKenzie
b91997354c v4.5.2 2015-02-26 09:04:05 +11:00
Sebastian McKenzie
4b8039a00c add 4.5.2 changelog 2015-02-26 09:00:37 +11:00
Sebastian McKenzie
0a0931dc2e add access to helpers used by the current file and allow a helper whitelist to be passed to buildHelpers - closes #898 2015-02-26 08:59:07 +11:00
Jamund Ferguson
24ace3c8c2 feat(6to5/register) don't override uncaughtException handler
Maybe we could do this by default or even make it configurable?
2015-02-25 13:51:26 -08:00
Sebastian McKenzie
372c06eb80 bump acorn-babel 2015-02-26 08:32:27 +11:00
Sebastian McKenzie
b8121ed4d0 Merge branch 'master' of github.com:6to5/6to5 2015-02-26 08:21:49 +11:00
Sebastian McKenzie
1f79445ee5 shim in function arity when proxying named functions - fixes #896 2015-02-26 08:21:37 +11:00
Sebastian McKenzie
cb46ca60af Merge pull request #894 from josh/travis-test-full-build
Test full `make build` on Travis
2015-02-26 08:05:24 +11:00
Joshua Peek
24c0c7679f Test full make build on travis 2015-02-25 10:23:42 -06:00
Ondrej Kraus
687b0f3180 remove unused function argument 2015-02-25 15:38:32 +01:00
Ondrej Kraus
e6855b974b update tests 2015-02-25 15:30:22 +01:00
Ondrej Kraus
a808742c19 remove strict-mode specific optimizations due to unsolvable ambiguities 2015-02-25 15:24:45 +01:00
Sebastian McKenzie
d7ec337567 move spec.functionName transformer to below validation transformers 2015-02-26 01:00:35 +11:00
Sebastian McKenzie
845f1ce65e remove linting since we're too bleeding edge :'( 2015-02-26 01:00:24 +11:00
Ondrej Kraus
c3f4091b6d replace for-of with with for for performance reasons 2015-02-25 14:41:20 +01:00
Ondrej Kraus
edb880f87c add tests 2015-02-25 14:26:28 +01:00
Ondrej Kraus
e8741daee3 use some ES6 to simplify code 2015-02-25 14:13:15 +01:00
Sebastian McKenzie
88563a0c26 add additional newline to alias functions transformer 2015-02-26 00:05:33 +11:00
Sebastian McKenzie
ccd7a6560c simplify README 2015-02-26 00:05:21 +11:00
Sebastian McKenzie
c340597fdb remove docs directory 2015-02-26 00:04:59 +11:00
Sebastian McKenzie
e498358125 classes... i just... no words 2015-02-25 23:47:01 +11:00
Ondrej Kraus
c5913564f8 replace quotes to conform to coding style 2015-02-25 13:34:18 +01:00
Ondrej Kraus
662bddbaca simplify optimization code 2015-02-25 13:34:17 +01:00
Ondrej Kraus
8f540dfff3 call non-strict mode optimizer before strict mode one to simplify literals 2015-02-25 13:34:17 +01:00
Ondrej Kraus
1265bc5a92 add better optimization when strictMode transformer is enabled 2015-02-25 13:34:15 +01:00
Ondrej Kraus
e677c72d58 add patterns support 2015-02-25 13:34:15 +01:00
Ondrej Kraus
8ca854156a simplify and optimize local binding handling 2015-02-25 13:34:14 +01:00
Ondrej Kraus
81ae656358 remove unused function 2015-02-25 13:34:13 +01:00
Ondrej Kraus
f2981b7e95 replace direct node type checking with helper functions 2015-02-25 13:34:12 +01:00
Ondrej Kraus
99b2e00d33 add rest parameters optimization 2015-02-25 13:34:11 +01:00
Sebastian McKenzie
25232d3141 use the mallet operator this is actually amazing i think i'm going to cry 2015-02-25 23:34:04 +11:00
Sebastian McKenzie
5b9878451a use strict BE GONE 2015-02-25 23:07:49 +11:00
Sebastian McKenzie
23d6fb6bb1 concise methods oh my god this is so good 2015-02-25 23:06:57 +11:00
Sebastian McKenzie
8d1b5c8ccb BOLD TEXT ALL UP IN THIS 2015-02-25 23:06:48 +11:00
Sebastian McKenzie
10bd7d1b91 4.5.1 2015-02-25 22:57:59 +11:00
Sebastian McKenzie
f5d9636353 v4.5.1 2015-02-25 22:55:50 +11:00
Sebastian McKenzie
a7f713ef5a remove jscs since it doesn't like arrow functions :( 2015-02-25 22:53:54 +11:00
Sebastian McKenzie
ba11069b1c utilise arrow functions omfg i love ES6 holy shit 2015-02-25 22:52:22 +11:00
Sebastian McKenzie
c13f8a3f50 update contributing guide 2015-02-25 22:43:40 +11:00
Sebastian McKenzie
339bd2b6d9 self-host #443 2015-02-25 22:36:23 +11:00
Sebastian McKenzie
a2843a5cb8 4.5.0 2015-02-25 22:03:38 +11:00
Sebastian McKenzie
c31832439a v4.5.0 2015-02-25 22:02:23 +11:00
Sebastian McKenzie
b7f19221a9 fix rc json error message 2015-02-25 22:00:32 +11:00
Sebastian McKenzie
46a37f4672 fix linting errors 2015-02-25 21:59:59 +11:00
Sebastian McKenzie
cfe2c19a02 fix linting errors 2015-02-25 21:57:49 +11:00
Sebastian McKenzie
649d91ef25 add 4.5.0 changelog 2015-02-25 21:56:23 +11:00
Sebastian McKenzie
4d72bffa30 add --copy-files bin/babel flag 2015-02-25 21:56:19 +11:00
Sebastian McKenzie
5889233adc rejigger path traversal class for es6ification 2015-02-25 21:50:40 +11:00
Sebastian McKenzie
7bb98352df add .babelrc - fixes #351 2015-02-25 21:49:48 +11:00
Sebastian McKenzie
12ebeed7c6 add missing extension to umd-strict formatter... - fixes #890 2015-02-25 19:10:20 +11:00
Sebastian McKenzie
7d87e52377 rejigger strict directives transformer logic so they're included in the body before module formatters are ran - @jayphelps 2015-02-25 17:20:23 +11:00
Sebastian McKenzie
2bab285970 temporarily disable own binding identification in nameMethod helper - fixes #871 2015-02-25 11:07:51 +11:00
Sebastian McKenzie
00651e671e don't copy over non-compilable files - fixes #888 2015-02-25 10:59:26 +11:00
Sebastian McKenzie
37588a6ceb 4.4.6 2015-02-24 22:17:46 +11:00
Sebastian McKenzie
a45d6960da v4.4.6 2015-02-24 22:17:12 +11:00
Sebastian McKenzie
b13aa41a75 fixing linting error 2015-02-24 22:15:27 +11:00
Sebastian McKenzie
20a4ed6140 add 4.4.6 changelog 2015-02-24 22:14:34 +11:00
Sebastian McKenzie
c256e060b3 Merge branch 'master' of github.com:6to5/6to5 2015-02-24 22:11:33 +11:00
Sebastian McKenzie
bef315efd6 fix up JSXElement alias keys 2015-02-24 22:11:25 +11:00
Sebastian McKenzie
2ec5390b63 bump core-js 2015-02-24 22:11:18 +11:00
Sebastian McKenzie
f4c9dd8768 Merge pull request #881 from sindresorhus/bump-chalk
bump `chalk`
2015-02-24 22:06:05 +11:00
Sindre Sorhus
510c7a3e60 bump chalk
https://github.com/sindresorhus/chalk/releases/tag/v1.0.0
2015-02-24 16:03:00 +07:00
Sebastian McKenzie
3ce9508a1c bump core-js @zloirock 2015-02-24 14:16:29 +11:00
Sebastian McKenzie
717ef280f7 clean up #870 2015-02-24 11:20:04 +11:00
Sebastian McKenzie
8c5e7cf272 Merge pull request #870 from neVERberleRfellerER/fix-extends-anon-class
fix extends with empty anonymous base class
2015-02-24 11:18:18 +11:00
Ondrej Kraus
811a843be9 add tests for extends of anonymous classes 2015-02-24 01:01:05 +01:00
Ondrej Kraus
b7c297bb89 remove anonymous class constructor name in specific case
Name of anonymous class constructor is not needed when it contains
exactly one method that is not construtor, because constructor
will be assigned to variable in closure.
2015-02-24 01:01:02 +01:00
Sebastian McKenzie
b7342ef4ea move es6.arrowFunctions transformer - fixes #874 2015-02-24 10:31:11 +11:00
Sebastian McKenzie
1a899f5e77 move attribute whitespace handling to JSXAttribute enter - fixes #872 2015-02-24 09:48:10 +11:00
Sebastian McKenzie
f2eb1643c0 throw deprecation error for @jsx React.DOM usage and crawl all comments for pragmas - fixes #876 2015-02-24 09:38:16 +11:00
neVERberleRfellerER
9621d1bbeb remove unnecessary derived class constructor name 2015-02-23 17:39:42 +01:00
Ondrej Kraus
3cf7b2b761 add name to constructor of extended anonymous class 2015-02-23 17:19:41 +01:00
Sebastian McKenzie
ae8b1e242b remove illegal left for of test 2015-02-23 21:36:42 +11:00
Sebastian McKenzie
eea48f866d allow MemberExpressions in for-of head 2015-02-23 21:31:57 +11:00
Sebastian McKenzie
84d2d7b7d4 add 4.4.5 changelog 2015-02-23 11:11:24 +11:00
Sebastian McKenzie
ea30a619dd bump regenerator-babel 2015-02-23 11:11:19 +11:00
Sebastian McKenzie
87a201db22 4.4.5 2015-02-22 23:27:02 +11:00
Sebastian McKenzie
bcc86c47bc v4.4.5 2015-02-22 23:26:01 +11:00
Sebastian McKenzie
b6df9b583b 4.4.4 2015-02-22 23:23:38 +11:00
Sebastian McKenzie
52ea7b5f59 always use closure wrap - fixes #864 2015-02-22 23:23:34 +11:00
Sebastian McKenzie
7bff8239a1 v4.4.4 2015-02-22 22:50:02 +11:00
Sebastian McKenzie
04d79c1740 fix array unpacking test 2015-02-22 22:46:27 +11:00
Sebastian McKenzie
e387da7c2b upgrade acorn-babel 2015-02-22 22:42:17 +11:00
Sebastian McKenzie
53cf453480 add 4.4.4 changelog 2015-02-22 22:40:18 +11:00
Sebastian McKenzie
341528ee4a fix linting errors 2015-02-22 22:37:51 +11:00
Sebastian McKenzie
5f6808ba92 don't transform flow module nodes 2015-02-22 22:35:47 +11:00
Sebastian McKenzie
0b2f1fedcb don't unpack array when the pattern contains more elements than the corresponding array expression 2015-02-22 22:35:38 +11:00
Sebastian McKenzie
c3c94f0a4a fix options argument to vm.runInThisContext 2015-02-22 22:35:04 +11:00
Sebastian McKenzie
f2d60aab9e optimise named functions depending on whether they contain an assignment/reference - #861 2015-02-22 21:35:08 +11:00
Sebastian McKenzie
ab6bb35a4f make line-numbers and js-tokens versions fixed 2015-02-22 20:55:09 +11:00
Sebastian McKenzie
e11b943514 revert to old named function wrapper - fixes #861 2015-02-22 20:54:47 +11:00
Sebastian McKenzie
b44a6eb297 remove is-keyword-js in favor of esutils #856 2015-02-22 10:51:27 +11:00
Sebastian McKenzie
f3288ddb1f Merge branch 'lydell-error-syntax-highlighting' 2015-02-22 10:49:30 +11:00
Simon Lydell
476aa44a90 improve syntax highlighting in error messages
- Support hexadecimal, octal and binary number literals, template strings, and
  tokenize everything more robustly in general.
- Tokens spanning over several lines (such as multiline strings and comments) no
  longer leak their color into the line number gutter.
- The color scheme is preserved.
- The line numbers are now right-aligned instead of left-aligned, since that's
  how practically every editor does it.
- Superfluos space in the line number gutter has been removed.
2015-02-21 21:20:52 +01:00
Sebastian McKenzie
c5589e9336 Merge pull request #853 from meandmycode/master
build: ensure bootstrap works on windows
2015-02-21 21:43:49 +11:00
Stephen Taylor
404eb2f972 build: ensure bootstrap works on windows 2015-02-21 10:17:28 +00:00
Sebastian McKenzie
366257915e advise users to visit the gitter room before creating an issue in the readme 2015-02-21 19:17:48 +11:00
Sebastian McKenzie
e0cd9bdbe3 4.4.3 2015-02-21 19:14:26 +11:00
Sebastian McKenzie
39854dc088 v4.4.3 2015-02-21 18:13:10 +11:00
Sebastian McKenzie
81132aa942 add 4.4.3 changelog 2015-02-21 18:08:32 +11:00
Sebastian McKenzie
5ba2e6254b check if iterator has a return method before calling it when breaking in a for...of - #838 2015-02-21 18:00:43 +11:00
Sebastian McKenzie
61ea720637 don't traverse into replacement breaks in for-of transformer - thanks @zloirock 2015-02-21 17:55:38 +11:00
Sebastian McKenzie
55357a331d rename selfContained transformer to runtime 2015-02-21 17:20:59 +11:00
Sebastian McKenzie
5deaeba3a0 4.4.2 2015-02-21 14:31:52 +11:00
Sebastian McKenzie
a38ae381e2 v4.4.2 2015-02-21 14:31:07 +11:00
Sebastian McKenzie
9a2e56f003 add moduleId option for specifying a custom module id 2015-02-21 14:29:26 +11:00
Sebastian McKenzie
5bc78b0237 4.4.1 2015-02-21 14:23:36 +11:00
Sebastian McKenzie
c5af8b8694 v4.4.1 2015-02-21 14:23:04 +11:00
Sebastian McKenzie
c637575cab remove tail-call template 2015-02-21 14:21:31 +11:00
Sebastian McKenzie
bc8d49c95c v4.4.0 2015-02-21 14:20:37 +11:00
Sebastian McKenzie
59ff0fd9a9 remove redundant esnext test 2015-02-21 14:18:53 +11:00
Sebastian McKenzie
b1f794eb84 fix linting errors 2015-02-21 14:16:02 +11:00
Sebastian McKenzie
79ab92b5d4 add 4.4.0 changelog 2015-02-21 14:14:50 +11:00
Sebastian McKenzie
f6512b45d5 coerce inferred function name to a valid identifier 2015-02-21 14:11:18 +11:00
Sebastian McKenzie
8065c981dc add iterator.return to for-of breaks - fixes #838 2015-02-21 13:31:14 +11:00
Sebastian McKenzie
7927aa2e18 make use strict directive stateless - fixes #828 2015-02-21 13:06:02 +11:00
Sebastian McKenzie
35bd510930 make react JSX transformer more generic and allow JSX comments - closes #841 2015-02-21 12:53:09 +11:00
Sebastian McKenzie
74186241f9 fix linting errors 2015-02-21 12:41:11 +11:00
Sebastian McKenzie
1effa72a33 remove format options but move compact option to main options 2015-02-21 12:41:03 +11:00
Sebastian McKenzie
b03a806d7c don't append a newline to the last switchcase 2015-02-21 12:27:38 +11:00
Sebastian McKenzie
6220fd9fc3 better control flow for tco continuation - fixes #850 and fixes #822 2015-02-21 12:27:24 +11:00
Sebastian McKenzie
8d92a75190 remove whitespace from the end of the last newline and improve newlines for switches 2015-02-21 03:22:44 +11:00
Sebastian McKenzie
60a7e40140 add website/docs issues reference to the readme 2015-02-21 02:24:28 +11:00
Sebastian McKenzie
299e462a29 unpack array rest elements when given a right hand array expression 2015-02-21 02:09:07 +11:00
Sebastian McKenzie
62556f6102 finish code generator revamp, output is now much nicer and liberal with it's use of newlines 2015-02-20 23:24:11 +11:00
Sebastian McKenzie
f2c5accab3 add getModuleName option - fixes #844 2015-02-20 23:23:50 +11:00
Sebastian McKenzie
15f1978cae Merge branch 'master' of github.com:6to5/6to5 2015-02-20 11:35:46 +11:00
Sebastian McKenzie
710ff548cb improve whitespace handling of code generator, reduce the use of lookaheads, add max newlines of 2 and better newline insertion for generated nodes 2015-02-20 11:35:27 +11:00
Sebastian McKenzie
fbb19fc656 clean up type alias keys 2015-02-20 11:34:43 +11:00
Sebastian McKenzie
e87ef80bc5 add back named methods for classes and add param binding check to spec.functionName transformer 2015-02-20 11:34:00 +11:00
Sebastian McKenzie
aca750e881 Merge pull request #839 from raganwald/patch-1
Links the babel logo in the readme to the home page
2015-02-20 08:00:26 +11:00
Reg Braithwaite
672e55082c link the babel logo in the readme to the home page 2015-02-19 15:46:35 -05:00
Sebastian McKenzie
a49f746700 add end_of_line = lf to editorconfig 2015-02-19 22:00:24 +11:00
Sebastian McKenzie
83cd3bef92 clean up destructuring transformer and optimise array destructuring - closes #749 2015-02-19 19:16:27 +11:00
Sebastian McKenzie
5e4a008a06 make code generator deopt on input >100KB 2015-02-19 10:48:08 +11:00
Sebastian McKenzie
1594efbc20 remove unused whitespace option 2015-02-19 10:47:51 +11:00
Sebastian McKenzie
002be9a05c enable spec.functionName by default 2015-02-19 10:47:44 +11:00
Sebastian McKenzie
8e06db8f7d remove minify binary 2015-02-19 10:47:08 +11:00
Sebastian McKenzie
b1238a1746 Merge branch 'master' of github.com:6to5/6to5 2015-02-19 10:46:47 +11:00
Ingvar Stepanyan
0874f390ff Add explicit return at the end of tail-recursive function.
Issue #822.
2015-02-18 14:44:47 +02:00
Sebastian McKenzie
eeff4ac9d1 add support for a string literal constructor name 2015-02-18 15:06:18 +11:00
Sebastian McKenzie
8f0ffc7302 4.3.0 2015-02-18 15:05:56 +11:00
Sebastian McKenzie
bb19649af8 v4.3.0 2015-02-18 13:15:45 +11:00
Sebastian McKenzie
692262df1b fix linting errors 2015-02-18 13:14:06 +11:00
Sebastian McKenzie
067047da34 update commonStandard tests to commonStrict 2015-02-18 13:10:25 +11:00
Sebastian McKenzie
1c5d169b1e 4.2.1 2015-02-18 13:08:36 +11:00
Sebastian McKenzie
3f82b4ec72 remove commonStandard module formatter and make it the default behaviour of all the strict module formatters 2015-02-18 13:08:25 +11:00
Sebastian McKenzie
9c6e632021 Merge pull request #785 from babel/fn-name
Set Function.name for funcs in variables and properties as per spec.
2015-02-18 11:49:52 +11:00
Sebastian McKenzie
45553f1fb7 v4.2.1 2015-02-18 11:37:47 +11:00
Sebastian McKenzie
f228edbb84 add auxiliary comment to let scoping closure flow control - fixes #819 2015-02-18 11:35:57 +11:00
Sebastian McKenzie
64e657e53d 4.2.0 2015-02-18 11:33:58 +11:00
Sebastian McKenzie
36423f2e78 v4.2.0 2015-02-18 11:28:53 +11:00
Sebastian McKenzie
06eaba5ad1 add 4.2.0 changelog 2015-02-18 11:26:46 +11:00
Sebastian McKenzie
7e8cd2ca8a i'm a terrible spellerer #777 2015-02-18 11:24:51 +11:00
Sebastian McKenzie
2541dcf960 bump acorn 2015-02-18 10:25:59 +11:00
Sebastian McKenzie
5d45e1475c Merge branch 'master' of github.com:6to5/6to5 2015-02-18 10:22:33 +11:00
Sebastian McKenzie
9964de9b2f remove redundant unknown transformer error message 2015-02-18 10:22:07 +11:00
Sebastian McKenzie
5b75b11628 add error message to use of eval(); and enable strict mode on the parser 2015-02-18 10:21:57 +11:00
Sebastian McKenzie
1890fb5bd3 add loose mode to __esModule 2015-02-18 10:21:32 +11:00
Sebastian McKenzie
df20b3df5a Merge pull request #815 from kolodny/iojs-test
add iojs to travis
2015-02-18 08:46:38 +11:00
Moshe Kolodny
56e74dfd10 add iojs to travis 2015-02-17 13:31:45 -05:00
Sebastian McKenzie
513d05143a 4.1.1 2015-02-18 00:01:55 +11:00
Sebastian McKenzie
84068943dd v4.1.1 2015-02-18 00:01:18 +11:00
Sebastian McKenzie
d3c75378ec v4.1.0 2015-02-17 23:59:38 +11:00
Sebastian McKenzie
ffe058bf69 add BABEL_CACHE_PATH and BABEL_DISABLE_CACHE environment variables 2015-02-17 23:06:19 +11:00
Sebastian McKenzie
765d95cd6f Merge branch 'master' of github.com:6to5/6to5 2015-02-17 16:57:26 +11:00
Sebastian McKenzie
33e82222ca remove 0.11 from travis.yml - #813, #807 2015-02-17 16:56:28 +11:00
Sebastian McKenzie
82d1c29696 Merge pull request #812 from sindresorhus/modularize-shebang-regex
modularize `SHEBANG_REGEX`
2015-02-17 16:33:12 +11:00
Sindre Sorhus
211c9802a5 modularize SHEBANG_REGEX
https://github.com/sindresorhus/shebang-regex
2015-02-17 12:26:36 +07:00
Sebastian McKenzie
f5a81e71bd Merge pull request #811 from sindresorhus/drop-helpers-clone
drop `helpers/clone`
2015-02-17 15:55:51 +11:00
Sindre Sorhus
4ea7a864fa drop helpers/clone
it's misleading as it doesn't actually do a deepClone, not even a clone
2015-02-17 11:42:24 +07:00
Sebastian McKenzie
d645659770 Merge pull request #810 from sindresorhus/modularize-normalisePathSeparator
modularize `normalisePathSeparator`
2015-02-17 15:24:06 +11:00
Sindre Sorhus
75ec9c8f2c modularize normalisePathSeparator
https://github.com/sindresorhus/slash
2015-02-17 11:19:12 +07:00
Sebastian McKenzie
3bffdc2be0 Merge pull request #809 from sindresorhus/modularize-isinteger
modularize `util.isInteger`
2015-02-17 15:12:18 +11:00
Sindre Sorhus
820db09613 modularize util.isInteger
https://github.com/parshap/js-is-integer
2015-02-17 11:10:00 +07:00
Sebastian McKenzie
f24ae6feab Merge pull request #808 from sindresorhus/modularize-trimright
modularize `util.trimRight`
2015-02-17 14:54:11 +11:00
Sindre Sorhus
5b09114b85 modularize util.trimRight
https://github.com/sindresorhus/trim-right
2015-02-17 10:51:02 +07:00
Sebastian McKenzie
28c948e5ea Merge pull request #806 from sindresorhus/modularize-isabsolute
modularize `util.isAbsolute`
2015-02-17 14:29:26 +11:00
Sindre Sorhus
bbf5a8f4aa modularize util.isAbsolute
by using a polyfill of the Node 0.12 `path.isAbsolute()` method

https://github.com/sindresorhus/path-is-absolute
2015-02-17 10:17:04 +07:00
Sebastian McKenzie
5f2865883b Merge branch 'master' of github.com:6to5/6to5 2015-02-17 14:09:49 +11:00
Sebastian McKenzie
c8433f950d fix 4.0.2 changelog... 2015-02-17 14:09:09 +11:00
Sebastian McKenzie
9135e700c6 Merge pull request #805 from sindresorhus/modularize-repeat
modularize `util.repeat`
2015-02-17 13:28:49 +11:00
Sindre Sorhus
eb17568c94 modularize util.repeat
https://github.com/sindresorhus/repeating
2015-02-17 09:25:00 +07:00
Sebastian McKenzie
407ff1e4a0 add 4.0.2 changelog 2015-02-17 13:12:31 +11:00
Sebastian McKenzie
fbaaf63c49 4.0.2 2015-02-17 13:11:15 +11:00
Sebastian McKenzie
f93daa3ca5 v4.0.2 2015-02-17 13:10:18 +11:00
Sebastian McKenzie
7fc1d04f9b Merge branch 'master' of github.com:6to5/6to5 2015-02-17 13:07:35 +11:00
Sebastian McKenzie
d6a34f02ca upgrade regenerator-babel #803 2015-02-17 13:07:22 +11:00
Sebastian McKenzie
fc3cb099c5 Merge pull request #802 from sindresorhus/sourcemapcomment
modularize the `sourceMapToComment` method
2015-02-17 12:49:12 +11:00
Sindre Sorhus
fc663d54fa modularize the sourceMapToComment method
https://github.com/sindresorhus/source-map-to-comment
2015-02-17 08:46:23 +07:00
Sebastian McKenzie
bf2418db66 set loose property assignments to computed if it's a literal 2015-02-17 10:45:24 +11:00
Sebastian McKenzie
5bd75db0b6 update setter validation error message 2015-02-17 09:34:45 +11:00
Sebastian McKenzie
13b3335a67 Merge pull request #800 from sindresorhus/remove-unused-deps
remove unused dependencies
2015-02-17 09:26:17 +11:00
Sindre Sorhus
4987f9e668 remove unused dependencies 2015-02-17 05:23:50 +07:00
Sebastian McKenzie
e585aa6bed use ranges for devDependencies 2015-02-17 09:23:48 +11:00
Sebastian McKenzie
d6c7be760b update settersInvalidParamLength error message - closes #797 2015-02-17 09:17:06 +11:00
Sebastian McKenzie
a19321ea69 update dependency ranges 2015-02-17 09:13:23 +11:00
Sebastian McKenzie
73fc1ac64e Merge pull request #794 from sindresorhus/bump-deps
bump dependencies
2015-02-17 09:11:10 +11:00
Sindre Sorhus
1d14764471 bump dependencies
The only breaking change is 599dd668fd and it doesn't affect `babel` since it doesn't use that property.
2015-02-17 05:02:32 +07:00
Sebastian McKenzie
e336ecd9cc Merge pull request #792 from sindresorhus/remove-moot-dep
Remove `supports-color` dependency as it's available in `chalk`
2015-02-17 08:53:42 +11:00
Sebastian McKenzie
5737a96f9f Merge pull request #793 from sindresorhus/levenshtein
Use `leven` module for levenshtein distance
2015-02-17 08:53:02 +11:00
Sebastian McKenzie
d7d4ec54cd Merge pull request #796 from richgilbank/babel-rename-makefile
Fix leftover `to5`
2015-02-17 08:49:18 +11:00
Rich Gilbank
98056e26af Update Makefile 2015-02-16 11:52:20 -05:00
Sindre Sorhus
afd07c9172 Use leven module for levenshtein distance
https://github.com/sindresorhus/leven

No point in bundling code like this.

Leven is also the fastest one: https://github.com/sindresorhus/leven#benchmark
2015-02-16 22:36:20 +07:00
Sindre Sorhus
af785126bf Remove supports-color dependency as it's available in chalk 2015-02-16 22:28:51 +07:00
Sebastian McKenzie
39c5849604 Merge branch 'master' of github.com:6to5/6to5 2015-02-16 14:37:08 +11:00
Sebastian McKenzie
1b6e465317 add email to license 2015-02-16 14:36:57 +11:00
Ingvar Stepanyan
17e65cc772 Set Function.name for funcs in variables and properties as per spec.
Implements correct Function.name for cases like following:
 * `var x = function () { ... }`
 * `var obj = {prop: function () { ... }}`
2015-02-15 23:43:17 +02:00
Sebastian McKenzie
15dff73cc8 Merge pull request #783 from mathiasbynens/patch-3
Update to regexpu v1.1.1
2015-02-16 03:05:59 +11:00
Mathias Bynens
186a15b3ce Update to regexpu v1.1.1 2015-02-15 17:05:35 +01:00
Sebastian McKenzie
610e52d767 4.0.1 2015-02-16 01:12:13 +11:00
Sebastian McKenzie
b0467fcb6d v4.0.1 2015-02-16 01:11:46 +11:00
Sebastian McKenzie
05be131647 rename bin tests to reflect new babel name 2015-02-16 01:08:26 +11:00
Sebastian McKenzie
f2300a5463 Revert "don't push array pattern uid if it's a local variable"
This reverts commit 86acc99fb3.
2015-02-16 01:06:14 +11:00
Sebastian McKenzie
86acc99fb3 don't push array pattern uid if it's a local variable 2015-02-16 01:01:42 +11:00
Sebastian McKenzie
21909cee76 rename runtime CLI flag to externalHelpers 2015-02-16 01:01:29 +11:00
Sebastian McKenzie
c97b53b52d fix 6to5 changelog 2015-02-16 01:01:14 +11:00
Sebastian McKenzie
c5e01146fd update rogue 6to5 occurences to babel 2015-02-15 20:39:46 +11:00
Sebastian McKenzie
010ff3ec31 reset transformer deprecation keys 2015-02-15 20:29:48 +11:00
Sebastian McKenzie
17532bfd82 update to 4.0.0 2015-02-15 19:54:14 +11:00
Sebastian McKenzie
545e9499c3 update readme to reflect babel name change 2015-02-15 19:54:08 +11:00
Sebastian McKenzie
02046c5448 rename runtime option to externalHelpers 2015-02-15 19:53:59 +11:00
Sebastian McKenzie
1d34d03ac8 rename to babel 2015-02-15 18:09:05 +11:00
Sebastian McKenzie
e05aed0394 support all loops when adding declarations - #779 2015-02-15 10:27:56 +11:00
Sebastian McKenzie
2d3b595a8b 3.6.5 2015-02-15 10:26:52 +11:00
Sebastian McKenzie
8f0b7683a1 v3.6.5 2015-02-14 23:05:13 +11:00
Sebastian McKenzie
f0d2cbb055 update 3.6.5 changelog 2015-02-14 22:57:57 +11:00
Sebastian McKenzie
602c5e0ca0 upgrade core-js 2015-02-14 22:56:49 +11:00
Sebastian McKenzie
2a2dff0eaf remap head variables when a closure is required in blockScoping transformer - fixes #763 2015-02-14 20:21:34 +11:00
Sebastian McKenzie
e1151e08c9 register default globals as bindings 2015-02-14 19:08:41 +11:00
Sebastian McKenzie
84f54ca3c7 rename defaultDeclarations to globals 2015-02-14 19:08:02 +11:00
Sebastian McKenzie
5fb793b75f add validation.react transformer 2015-02-14 19:07:54 +11:00
Sebastian McKenzie
1adc9bfc70 use t.buildMatchMemberExpression in selfContained transformer 2015-02-14 19:07:46 +11:00
Sebastian McKenzie
3649fad485 ensureBlock on if statements with expression return statements - fixes #764 2015-02-14 19:07:23 +11:00
Sebastian McKenzie
0e1743738e add auxilary comment option to prepend to helpers - #777 2015-02-14 16:53:41 +11:00
Sebastian McKenzie
6ad16302cd update 3.6.3 changelog 2015-02-14 13:29:57 +11:00
Sebastian McKenzie
4b6b7af332 3.6.4 2015-02-14 13:29:52 +11:00
Sebastian McKenzie
55dfb423ee v3.6.4 2015-02-14 13:26:59 +11:00
Sebastian McKenzie
9d1bc4817d fix flow module type stripping 2015-02-14 13:24:39 +11:00
Sebastian McKenzie
fc8666e7a4 3.6.3 2015-02-14 13:22:18 +11:00
Sebastian McKenzie
07b6881d67 add support for flow type casts and module types 2015-02-14 13:22:13 +11:00
768 changed files with 12947 additions and 9483 deletions

View File

@@ -1,5 +1,6 @@
{
"experimental": true,
"playground": true,
"loose": true
"loose": true,
"blacklist": ["es6.tailCall"]
}

View File

@@ -5,6 +5,7 @@ insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf
[*.{js,json}]
indent_style = space

1
.eslintignore Normal file
View File

@@ -0,0 +1 @@
src/babel/transformation/templates

22
.eslintrc Normal file
View File

@@ -0,0 +1,22 @@
{
"parser": "babel-eslint",
"rules": {
"strict": 0,
"no-underscore-dangle": 0,
"no-unused-vars": 0,
"curly": 0,
"no-multi-spaces": 0,
"key-spacing": 0,
"no-return-assign": 0,
"consistent-return": 0,
"no-shadow": 0,
"no-comma-dangle": 0,
"no-use-before-define": 0,
"no-empty": 0,
"new-parens": 0,
"no-cond-assign": 0
},
"env": {
"node": true
}
}

6
.gitignore vendored
View File

@@ -11,5 +11,7 @@ test/tmp
coverage
dist
.package.json
packages/6to5-runtime/*.js
packages/6to5-runtime/regenerator/*.js
packages/babel-runtime/*.js
packages/babel-runtime/helpers/*.js
packages/babel-runtime/regenerator/*.js
lib

2
.gitmodules vendored
View File

@@ -3,7 +3,7 @@
url = https://github.com/google/traceur-compiler
[submodule "vendor/regenerator"]
path = vendor/regenerator
url = https://github.com/6to5/regenerator-6to5
url = https://github.com/babel/regenerator-babel
[submodule "vendor/test262"]
path = vendor/test262
url = https://github.com/tc39/test262

58
.jscsrc
View File

@@ -1,58 +0,0 @@
{
"excludeFiles": ["lib/6to5/transformation/templates"],
"disallowSpacesInNamedFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"requireSpacesInAnonymousFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"requireSpacesInAnonymousFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInFunctionDeclaration": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInsideArrayBrackets": true,
"disallowSpacesInsideParentheses": true,
"disallowSpaceAfterObjectKeys": true,
"disallowSpaceAfterPrefixUnaryOperators": true,
"disallowSpaceBeforePostfixUnaryOperators": true,
"disallowSpaceBeforeBinaryOperators": [
","
],
"disallowMixedSpacesAndTabs": true,
"disallowTrailingWhitespace": true,
"disallowYodaConditions": true,
"disallowKeywords": [ "with" ],
"disallowMultipleLineBreaks": true,
"requireSpaceBeforeBlockStatements": true,
"requireParenthesesAroundIIFE": true,
"requireSpacesInConditionalExpression": true,
"requireBlocksOnNewline": 1,
"requireCommaBeforeLineBreak": true,
"requireSpaceBeforeBinaryOperators": true,
"requireSpaceAfterBinaryOperators": true,
"requireLineFeedAtFileEnd": true,
"requireCapitalizedConstructors": true,
"requireSpacesInForStatement": true,
"requireCurlyBraces": [
"do"
],
"requireSpaceAfterKeywords": [
"if",
"else",
"for",
"while",
"do",
"switch",
"case",
"return",
"try",
"catch",
"typeof",
"function"
],
"validateLineBreaks": "LF",
"validateQuoteMarks": "\"",
"validateIndentation": 2
}

View File

@@ -1 +0,0 @@
lib/6to5/transformation/templates

View File

@@ -1,27 +0,0 @@
{
"esnext": true,
"indent": 2,
"freeze": true,
"validthis": true,
"camelcase": true,
"unused": true,
"eqnull": true,
"newcap": true,
"supernew": true,
"noyield": true,
"evil": true,
"node": true,
"boss": true,
"expr": true,
"undef": true,
"maxparams": 5,
"maxdepth": 4,
"globals": {
"window": true,
"suite": true,
"set": true,
"before": true,
"bench": true
}
}

View File

@@ -1,7 +1,7 @@
node_modules
*.log
*.cache
lib/6to5/transformation/templates
lib/babel/transformation/templates
test
benchmark
Makefile
@@ -13,3 +13,4 @@ CHANGELOG.md
coverage
vendor
packages
src

View File

@@ -1,9 +1,8 @@
sudo: false
language: node_js
node_js:
- "0.10"
- "0.11"
- "0.12"
- "iojs"
branches:
except:

1093
CHANGELOG-6to5.md Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -2,29 +2,57 @@
Contributions are always welcome, no matter how large or small. Before
contributing, please read the
[code of conduct](https://github.com/6to5/6to5/blob/master/CODE_OF_CONDUCT.md).
**NOTE:** Please do not send pull requests that fix linting issues. It's highly
likely that they've already been fixed by the time it's submitted and it just
pollutes the git tree.
[code of conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md).
## Developing
#### Setup
```sh
$ git clone https://github.com/babel/babel
$ cd babel
$ make bootstrap
```
Then you need to run:
```sh
$ make watch-core
```
This will compile babel and then sit in the background and on file modification
recompile the necessary files.
#### Running tests
You can run tests via:
```sh
$ make test
```
This will usually take around two minutes as it's compiling the entire
[test262](https://github.com/tc39/test262) test suite and validating it's AST.
This is mostly overkill and you can limit the tests to a select few by directly
running them with `mocha`:
```sh
$ mocha test/transformation.js
```
#### Workflow
* Fork the repository
* Clone your fork and change directory to it (`git clone git@github.com:yourUserName/6to5.git && cd 6to5`)
* Clone your fork and change directory to it (`git clone git@github.com:yourUserName/babel.git && cd babel`)
* Install the project dependencies (`make bootstrap`)
* Link your forked clone (`npm link`)
* Develop your changes ensuring you're fetching updates from upstream often
* Ensure the test are passing (`make test`)
* Create new pull request explaining your proposed change or reference an issue
in your commit message
* Create new pull request explaining your proposed change or reference an issue in your commit message
#### Code Standards
* **General**
* No ES6 syntax features or methods, exclusively ES5.
* Max of five arguments for functions
* Max depth of four nested blocks
* 2-spaced soft tabs
@@ -43,11 +71,3 @@ pollutes the git tree.
* **Declaration**
* No unused variables
* No pollution of global variables and prototypes
## Testing
$ make test
## Linting
$ make lint

View File

@@ -1,4 +1,4 @@
Copyright (c) 2014-2015 Sebastian McKenzie
Copyright (c) 2014-2015 Sebastian McKenzie <sebmck@gmail.com>
MIT License

View File

@@ -4,74 +4,65 @@ UGLIFY_CMD = node_modules/uglify-js/bin/uglifyjs
#UGLIFY_CMD = node_modules/uglify-js/bin/uglifyjs --mangle sort
JSHINT_CMD = node_modules/jshint/bin/jshint
MOCHA_CMD = node_modules/mocha/bin/_mocha
JSCS_CMD = node_modules/jscs/bin/jscs
6TO5_CMD = node_modules/6to5/bin/6to5
BABEL_CMD = node_modules/babel/bin/babel
export NODE_ENV = test
.PHONY: clean test test-cov test-clean lint test-travis test-simple test-all test-browser publish build bootstrap publish-core publish-runtime build-core watch-core
.PHONY: clean test test-cov test-clean test-travis test-simple test-all test-browser publish build bootstrap publish-core publish-runtime build-core watch-core build-core-test
build-core:
#node $(6TO5_CMD) src --out-dir lib
node $(BABEL_CMD) src --out-dir lib --copy-files
build-core-test:
node $(BABEL_CMD) src --out-dir lib --copy-files --auxiliary-comment "istanbul ignore next"
watch-core:
#node $(6TO5_CMD) src --out-dir lib --watch
node $(BABEL_CMD) src --out-dir lib --watch --copy-files
build:
mkdir -p dist
make build-core
node tools/cache-templates
node $(BROWSERIFY_CMD) -e lib/6to5/polyfill.js >dist/polyfill.js
node $(BROWSERIFY_CMD) -e lib/babel/polyfill.js >dist/polyfill.js
node $(UGLIFY_CMD) dist/polyfill.js >dist/polyfill.min.js
node $(BROWSERIFY_CMD) lib/6to5/api/browser.js -s to5 >dist/6to5.js
node $(UGLIFY_CMD) dist/6to5.js >dist/6to5.min.js
node $(BROWSERIFY_CMD) lib/babel/api/browser.js -s babel >dist/babel.js
node $(UGLIFY_CMD) dist/babel.js >dist/babel.min.js
node bin/6to5-runtime >dist/runtime.js
node $(UGLIFY_CMD) dist/runtime.js >dist/runtime.min.js
node bin/babel-external-helpers >dist/external-helpers.js
node $(UGLIFY_CMD) dist/external-helpers.js >dist/external-helpers.min.js
rm -rf templates.json
clean:
rm -rf coverage templates.json test/tmp dist
lint:
$(JSHINT_CMD) --reporter node_modules/jshint-stylish/stylish.js lib bin
$(JSCS_CMD) lib bin
test-clean:
rm -rf test/tmp
test: lint
$(MOCHA_CMD)
test:
node $(MOCHA_CMD)
make test-clean
test-simple:
# excludes test262
export SIMPLE_6TO5_TESTS=1; \
make test
test-all:
# includes traceur, esnext, regenerator
export ALL_6TO5_TESTS=1; \
export ALL_BABEL_TESTS=1; \
make test
test-cov:
rm -rf coverage
export SIMPLE_6TO5_TESTS=1; \
make build-core-test
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
test-travis: build-core bootstrap
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
if test -n "$$CODECLIMATE_REPO_TOKEN"; then codeclimate < coverage/lcov.info; fi
test-travis: bootstrap build test
test-browser:
mkdir -p dist
node tools/cache-templates
node tools/cache-tests
node $(BROWSERIFY_CMD) -e test/_browser.js >dist/6to5-test.js
node $(BROWSERIFY_CMD) -e test/_browser.js >dist/babel-test.js
rm -rf templates.json tests.json
test -n "`which open`" && open test/browser.html
@@ -85,9 +76,9 @@ publish:
npm version $$version --message "v%s"
make build
cp dist/6to5.min.js browser.js
cp dist/babel.min.js browser.js
cp dist/polyfill.min.js browser-polyfill.js
cp dist/runtime.min.js runtime.js
cp dist/external-helpers.min.js external-helpers.js
node tools/cache-templates
test -f templates.json
@@ -99,12 +90,12 @@ publish:
make publish-core
make publish-runtime
rm -rf templates.json browser.js browser-polyfill.js runtime.js
rm -rf templates.json browser.js browser-polyfill.js external-helpers.js
publish-runtime:
cd packages; \
node build-runtime.js; \
cd 6to5-runtime; \
cd babel-runtime; \
npm publish
publish-core:
@@ -120,5 +111,5 @@ publish-core:
bootstrap:
npm install
git submodule update --init
cd vendor/regenerator; npm install
cd vendor/compat-table; npm install object-assign
cd vendor/regenerator && npm install
cd vendor/compat-table && npm install object-assign

View File

@@ -1,3 +0,0 @@
# Notes
* Wildcard exports/imports wont normalize if `export default` is a non-object. See [#224](https://github.com/6to5/6to5/issues/224).

View File

@@ -1,12 +1,17 @@
<p align="center">
<img alt="6to5" src="https://raw.githubusercontent.com/6to5/logo/master/logo.png" width="546">
<a href="https://babeljs.io/">
<img alt="babel" src="https://raw.githubusercontent.com/babel/logo/master/logo.png" width="546">
</a>
</p>
<p align="center">
<strong>6to5</strong> turns ES6+ code into vanilla ES5, so you can use next generation features <strong>today.</strong>
<strong>Babel</strong> is a transpiler for writing next generation JavaScript.
</p>
<p align="center">
For more information view the <a href="https://6to5.github.io">documentation</a>. For
support visit the <a href="https://gitter.im/6to5/6to5">gitter room</a>.
For questions and support please visit the <a href="https://gitter.im/babel/babel">gitter room</a> before creating an issue.
</p>
<p align="center">
For documentation and website issues please visit the <a href="https://github.com/babel/babel.github.io">babel.github.io</a> repo.
</p>

View File

@@ -1,7 +0,0 @@
#!/usr/bin/env node
var opts = require("./6to5").opts;
opts.optional = (opts.optional || []).concat("minification");
opts.format = {
compact: true
};

View File

@@ -1,4 +0,0 @@
#!/usr/bin/env node
var runtime = require("../lib/6to5/build-runtime");
console.log(runtime());

View File

@@ -1,15 +1,16 @@
#!/usr/bin/env node
var commander = require("commander");
var Module = require("module");
var path = require("path");
var repl = require("repl");
var to5 = require("../lib/6to5/api/node");
var util = require("../lib/6to5/util");
var vm = require("vm");
var _ = require("lodash");
var pathIsAbsolute = require("path-is-absolute");
var commander = require("commander");
var Module = require("module");
var babel = require("../lib/babel/api/node");
var path = require("path");
var repl = require("repl");
var util = require("../lib/babel/util");
var vm = require("vm");
var _ = require("lodash");
var program = new commander.Command("6to5-node");
var program = new commander.Command("babel-node");
program.option("-e, --eval [script]", "Evaluate script");
program.option("-p, --print [code]", "Evaluate script and print result");
@@ -28,7 +29,7 @@ program.parse(process.argv);
//
to5.register({
babel.register({
experimental: program.experimental,
extensions: program.extensions,
playground: program.playground,
@@ -41,7 +42,7 @@ to5.register({
//
var _eval = function (code, filename) {
code = to5.transform(code, {
code = babel.transform(code, {
filename: filename,
blacklist: ["useStrict"].concat(program.blacklist || []),
whitelist: program.whitelist,
@@ -49,18 +50,32 @@ var _eval = function (code, filename) {
experimental: program.experimental,
playground: program.playground
}).code;
return vm.runInThisContext(code, filename);
return vm.runInThisContext(code, {
filename: filename
});
};
if (program.eval || program.print) {
var code = program.eval;
if (!code || code === true) code = program.print;
var result = _eval(code, "eval");
global.__filename = "[eval]";
global.__dirname = process.cwd();
var module = new Module(global.__filename);
module.filename = global.__filename;
module.paths = Module._nodeModulePaths(global.__dirname);
global.exports = module.exports;
global.module = module;
global.require = module.require.bind(module);
var result = _eval(code, global.__filename);
if (program.print) console.log(result);
} else {
if (program.args.length) {
// slice all arguments up to the first filename since they're 6to5 args that we handle
// slice all arguments up to the first filename since they're babel args that we handle
var args = process.argv.slice(2);
var i = 0;
@@ -84,8 +99,8 @@ if (program.eval || program.print) {
args = args.slice(i);
// make the filename absolute
var filename = args[0]
if (!util.isAbsolute(filename)) args[0] = path.join(process.cwd(), filename);
var filename = args[0];
if (!pathIsAbsolute(filename)) args[0] = path.join(process.cwd(), filename);
// add back on node and concat the sliced args
process.argv = ["node"].concat(args);

13
bin/babel-external-helpers Executable file
View File

@@ -0,0 +1,13 @@
#!/usr/bin/env node
var commander = require("commander");
var util = require("../lib/babel/util");
var runtime = require("../lib/babel/build-external-helpers");
commander.option("-l, --whitelist [whitelist]", "Whitelist of helpers to ONLY include", util.list);
commander.option("-t, --output-type [type]", "Type of output (global|umd|var)", "global");
commander.usage("[options]");
commander.parse(process.argv);
console.log(runtime(commander.whitelist, commander.outputType));

View File

@@ -2,12 +2,22 @@
/**
* This tiny wrapper file checks for known node flags and appends them
* when found, before invoking the "real" _6to5-node(1) executable.
* when found, before invoking the "real" _babel-node(1) executable.
*/
var args = [__dirname + "/_6to5-node"];
var args = [__dirname + "/_babel-node"];
process.argv.slice(2).forEach(function(arg){
var babelArgs = process.argv.slice(2);
var userArgs;
// separate node arguments from script arguments
var argSeparator = babelArgs.indexOf("--");
if (argSeparator > -1) {
userArgs = babelArgs.slice(argSeparator); // including the --
babelArgs = babelArgs.slice(0, argSeparator);
}
babelArgs.forEach(function(arg){
var flag = arg.split("=")[0];
switch (flag) {
@@ -49,6 +59,11 @@ process.argv.slice(2).forEach(function(arg){
}
});
// append arguments passed after --
if (argSeparator > -1) {
args = args.concat(userArgs);
}
try {
var kexec = require("kexec");
kexec(process.argv[0], args);

View File

@@ -31,6 +31,14 @@ module.exports = function (commander, filenames, opts) {
console.log(src + " -> " + dest);
};
var handleFile = function (src, filename) {
if (util.canCompile(filename)) {
write(src, filename);
} else if (commander.copyFiles) {
outputFileSync(path.join(commander.outDir, filename), fs.readFileSync(src));
}
};
var handle = function (filename) {
if (!fs.existsSync(filename)) return;
@@ -41,11 +49,7 @@ module.exports = function (commander, filenames, opts) {
_.each(util.readdir(dirname), function (filename) {
var src = path.join(dirname, filename);
if (util.canCompile(filename)) {
write(src, filename);
} else {
outputFileSync(path.join(commander.outDir, filename), fs.readFileSync(src));
}
handleFile(src, filename);
});
} else {
write(filename, filename);
@@ -64,7 +68,11 @@ module.exports = function (commander, filenames, opts) {
_.each(["add", "change"], function (type) {
watcher.on(type, function (filename) {
var relative = path.relative(dirname, filename) || filename;
write(filename, relative);
try {
handleFile(filename, relative);
} catch (err) {
console.error(err.stack);
}
});
});
});

View File

@@ -1,10 +1,10 @@
var sourceMap = require("source-map");
var chokidar = require("chokidar");
var util2 = require("../../lib/6to5/util");
var path = require("path");
var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
var convertSourceMap = require("convert-source-map");
var sourceMap = require("source-map");
var chokidar = require("chokidar");
var path = require("path");
var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
module.exports = function (commander, filenames) {
var results = [];
@@ -42,7 +42,7 @@ module.exports = function (commander, filenames) {
});
if (commander.sourceMapsInline || (!commander.outFile && commander.sourceMaps)) {
code += "\n" + util2.sourceMapToComment(map);
code += "\n" + convertSourceMap.fromObject(map).toComment();
}
return {
@@ -119,7 +119,11 @@ module.exports = function (commander, filenames) {
}).on("all", function (type, filename) {
if (type === "add" || type === "change") {
console.log(type, filename);
walk();
try {
walk();
} catch (err) {
console.error(err.stack);
}
}
});
}

View File

@@ -1,8 +1,8 @@
#!/usr/bin/env node
var commander = require("commander");
var transform = require("../../lib/6to5/transformation");
var util = require("../../lib/6to5/util");
var transform = require("../../lib/babel/transformation");
var util = require("../../lib/babel/util");
var fs = require("fs");
var each = require("lodash/collection/each");
var keys = require("lodash/object/keys");
@@ -11,10 +11,11 @@ commander.option("-t, --source-maps-inline", "Append sourceMappingURL comment to
commander.option("-s, --source-maps", "Save source map alongside the compiled code");
commander.option("-f, --filename [filename]", "Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]", "stdin");
commander.option("-w, --watch", "Recompile files on changes");
commander.option("-r, --runtime", "Replace 6to5 declarations with references to a runtime");
commander.option("-r, --external-helpers", "Replace helpers with references to a `babelHelpers` global");
commander.option("-e, --experimental", "Enable experimental support for proposed ES7 features");
commander.option("-p, --playground", "Enable playground support");
commander.option("-c, --compact [mode]", "When set to \"auto\" compact is `true` when the input size exceeds 100KB. (auto|true|false)", "auto");
commander.option("-m, --modules [modules]", "Module formatter type to use [common]", "common");
commander.option("-l, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", util.list);
commander.option("-b, --blacklist [blacklist]", "Blacklist of transformers to NOT use", util.list);
@@ -26,6 +27,8 @@ commander.option("-c, --remove-comments", "Remove comments from the compiled cod
commander.option("-M, --module-ids", "Insert module id in modules", false);
commander.option("-R, --react-compat", "Makes the react transformer produce pre-v0.12 code");
commander.option("--keep-module-id-extensions", "Keep extensions when generating module ids", false);
commander.option("-a, --auxiliary-comment [comment]", "Comment text to prepend to all auxiliary code");
commander.option("-D, --copy-files", "When compiling a directory copy over non-compilable files");
commander.on("--help", function () {
var outKeys = function (title, obj) {
@@ -99,6 +102,8 @@ if (errors.length) {
exports.opts = {
keepModuleIdExtensions: commander.keepModuleIdExtensions,
auxiliaryComment: commander.auxiliaryComment,
externalHelpers: commander.externalHelpers,
sourceMapName: commander.outFile,
experimental: commander.experimental,
reactCompat: commander.reactCompat,
@@ -109,22 +114,17 @@ exports.opts = {
sourceMap: commander.sourceMaps || commander.sourceMapsInline,
optional: commander.optional,
comments: !commander.removeComments,
runtime: commander.runtime,
modules: commander.modules,
compact: commander.compact,
loose: commander.loose
};
setTimeout(function () {
// this is just a hack to give `6to5-minify` and other files including this
// time to modify `exports.opts`
var fn;
var fn;
if (commander.outDir) {
fn = require("./dir");
} else {
fn = require("./file");
}
if (commander.outDir) {
fn = require("./dir");
} else {
fn = require("./file");
}
fn(commander, filenames, exports.opts);
}, 0);
fn(commander, filenames, exports.opts);

View File

@@ -1,10 +1,11 @@
var readdir = require("fs-readdir-recursive");
var index = require("./index");
var util = require("../../lib/6to5/util");
var path = require("path");
var to5 = require("../../lib/6to5/api/node");
var fs = require("fs");
var _ = require("lodash");
var resolveRc = require("../../lib/babel/api/register/resolve-rc");
var readdir = require("fs-readdir-recursive");
var index = require("./index");
var babel = require("../../lib/babel/api/node");
var util = require("../../lib/babel/util");
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
exports.readdirFilter = function (filename) {
return readdir(filename).filter(function (filename) {
@@ -23,18 +24,9 @@ exports.addSourceMappingUrl = function (code, loc) {
exports.transform = function (filename, code, opts) {
opts = _.defaults(opts || {}, index.opts);
opts.filename = filename;
resolveRc(filename, opts);
var result;
try {
result = to5.transform(code, opts);
} catch (e) {
if (e instanceof SyntaxError) {
console.error("SyntaxError:", e.message);
process.exit(1);
} else {
throw e;
}
}
var result = babel.transform(code, opts);
result.filename = filename;
result.actual = code;
return result;

3
bin/deprecated/6to5 Executable file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
console.error("`6to5` has been renamed to `babel`");
require("../babel");

3
bin/deprecated/6to5-node Executable file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
console.error("`6to5-node` has been renamed to `babel-node`");
require("../_babel-node");

3
bin/deprecated/6to5-runtime Executable file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
console.error("`6to5-runtime` has been renamed to `babel-external-helpers`");
require("../babel-external-helpers");

View File

@@ -1 +0,0 @@
See [6to5.github.io/docs](https://github.com/6to5/6to5.github.io/tree/master/docs).

View File

@@ -1,58 +0,0 @@
"use strict";
var isFunction = require("lodash/lang/isFunction");
var transform = require("../transformation");
var util = require("../util");
var fs = require("fs");
exports.version = require("../../../package").version;
exports.runtime = require("../build-runtime");
exports.types = require("../types");
exports.register = function (opts) {
var register = require("./register/node");
if (opts != null) register(opts);
return register;
};
exports.polyfill = function () {
require("../polyfill");
};
exports.canCompile = util.canCompile;
// do not use this - this is for use by official maintained 6to5 plugins
exports._util = util;
exports.transform = transform;
exports.transformFile = function (filename, opts, callback) {
if (isFunction(opts)) {
callback = opts;
opts = {};
}
opts.filename = filename;
fs.readFile(filename, function (err, code) {
if (err) return callback(err);
var result;
try {
result = transform(code, opts);
} catch (err) {
return callback(err);
}
callback(null, result);
});
};
exports.transformFileSync = function (filename, opts) {
opts = opts || {};
opts.filename = filename;
return transform(fs.readFileSync(filename), opts);
};

View File

@@ -1,7 +0,0 @@
"use strict";
// required to safely use 6to5/register within a browserify codebase
module.exports = function () {};
require("../../polyfill");

View File

@@ -1,13 +0,0 @@
var File = require("./transformation/file");
var util = require("./util");
var each = require("lodash/collection/each");
var t = require("./types");
module.exports = function (body, namespace) {
each(File.helpers, function (name) {
var key = t.identifier(t.toIdentifier(name));
body.push(t.expressionStatement(
t.assignmentExpression("=", t.memberExpression(namespace, key), util.template(name))
));
});
};

View File

@@ -1,25 +0,0 @@
"use strict";
var buildHelpers = require("./build-helpers");
var generator = require("./generation");
var util = require("./util");
var t = require("./types");
module.exports = function () {
var namespace = t.identifier("to5Runtime");
var body = [];
var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
var tree = t.program([t.expressionStatement(t.callExpression(container, [util.template("self-global")]))]);
body.push(t.variableDeclaration("var", [
t.variableDeclarator(
namespace,
t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([]))
)
]));
buildHelpers(body, namespace);
return generator(tree).code;
};

View File

@@ -1,166 +0,0 @@
"use strict";
module.exports = Buffer;
var isBoolean = require("lodash/lang/isBoolean");
var includes = require("lodash/collection/includes");
var isNumber = require("lodash/lang/isNumber");
var util = require("../util");
function Buffer(position, format) {
this.position = position;
this._indent = format.indent.base;
this.format = format;
this.buf = "";
}
Buffer.prototype.get = function () {
return util.trimRight(this.buf);
};
Buffer.prototype.getIndent = function () {
if (this.format.compact || this.format.concise) {
return "";
} else {
return util.repeat(this._indent, this.format.indent.style);
}
};
Buffer.prototype.indentSize = function () {
return this.getIndent().length;
};
Buffer.prototype.indent = function () {
this._indent++;
};
Buffer.prototype.dedent = function () {
this._indent--;
};
Buffer.prototype.semicolon = function () {
this.push(";");
};
Buffer.prototype.ensureSemicolon = function () {
if (!this.isLast(";")) this.semicolon();
};
Buffer.prototype.rightBrace = function () {
this.newline(true);
this.push("}");
};
Buffer.prototype.keyword = function (name) {
this.push(name);
this.space();
};
Buffer.prototype.space = function () {
if (this.format.compact) return;
if (this.buf && !this.isLast([" ", "\n"])) {
this.push(" ");
}
};
Buffer.prototype.removeLast = function (cha) {
if (!this.isLast(cha)) return;
this.buf = this.buf.substr(0, this.buf.length - 1);
this.position.unshift(cha);
};
Buffer.prototype.newline = function (i, removeLast) {
if (this.format.compact || this.format.concise) {
this.space();
return;
}
removeLast = removeLast || false;
if (isNumber(i)) {
if (this.endsWith("{\n")) i--;
if (this.endsWith(util.repeat(i, "\n"))) return;
while (i--) {
this._newline(removeLast);
}
return;
}
if (isBoolean(i)) {
removeLast = i;
}
this._newline(removeLast);
};
Buffer.prototype._newline = function (removeLast) {
if (removeLast && this.isLast("\n")) this.removeLast("\n");
this.removeLast(" ");
// remove whitespace if last character was a newline
this._removeSpacesAfterLastNewline();
this._push("\n");
};
/**
* If buffer ends with a newline and some spaces after it, trim those spaces.
*/
Buffer.prototype._removeSpacesAfterLastNewline = function () {
var lastNewlineIndex = this.buf.lastIndexOf("\n");
if (lastNewlineIndex === -1)
return;
var index = this.buf.length - 1;
while (index > lastNewlineIndex) {
if (this.buf[index] !== " ") {
break;
}
index--;
}
if (index === lastNewlineIndex) {
this.buf = this.buf.substring(0, index + 1);
}
};
Buffer.prototype.push = function (str, noIndent) {
if (this._indent && !noIndent && str !== "\n") {
// we have an indent level and we aren't pushing a newline
var indent = this.getIndent();
// replace all newlines with newlines with the indentation
str = str.replace(/\n/g, "\n" + indent);
// we've got a newline before us so prepend on the indentation
if (this.isLast("\n")) str = indent + str;
}
this._push(str);
};
Buffer.prototype._push = function (str) {
this.position.push(str);
this.buf += str;
};
Buffer.prototype.endsWith = function (str) {
var d = this.buf.length - str.length;
return d >= 0 && this.buf.lastIndexOf(str) === d;
};
Buffer.prototype.isLast = function (cha, trimRight) {
var buf = this.buf;
if (trimRight) buf = util.trimRight(buf);
var last = buf[buf.length - 1];
if (Array.isArray(cha)) {
return includes(cha, last);
} else {
return cha === last;
}
};

View File

@@ -1,35 +0,0 @@
"use strict";
exports.AnyTypeAnnotation =
exports.ArrayTypeAnnotation =
exports.BooleanTypeAnnotation =
exports.ClassProperty =
exports.DeclareClass =
exports.DeclareFunction =
exports.DeclareModule =
exports.DeclareVariable =
exports.FunctionTypeAnnotation =
exports.FunctionTypeParam =
exports.GenericTypeAnnotation =
exports.InterfaceExtends =
exports.InterfaceDeclaration =
exports.IntersectionTypeAnnotation =
exports.NullableTypeAnnotation =
exports.NumberTypeAnnotation =
exports.StringLiteralTypeAnnotation =
exports.StringTypeAnnotation =
exports.TupleTypeAnnotation =
exports.TypeofTypeAnnotation =
exports.TypeAlias =
exports.TypeAnnotation =
exports.TypeParameterDeclaration =
exports.TypeParameterInstantiation =
exports.ObjectTypeAnnotation =
exports.ObjectTypeCallProperty =
exports.ObjectTypeIndexer =
exports.ObjectTypeProperty =
exports.QualifiedTypeIdentifier =
exports.UnionTypeAnnotation =
exports.VoidTypeAnnotation = function () {
// todo: implement these once we have a `--keep-types` option
};

View File

@@ -1,9 +0,0 @@
"use strict";
var each = require("lodash/collection/each");
each(["BindMemberExpression", "BindFunctionExpression"], function (type) {
exports[type] = function () {
throw new ReferenceError("Trying to render non-standard playground node " + JSON.stringify(type));
};
});

View File

@@ -1,32 +0,0 @@
"use strict";
var each = require("lodash/collection/each");
exports.TaggedTemplateExpression = function (node, print) {
print(node.tag);
print(node.quasi);
};
exports.TemplateElement = function (node) {
this._push(node.value.raw);
};
exports.TemplateLiteral = function (node, print) {
this.push("`");
var quasis = node.quasis;
var self = this;
var len = quasis.length;
each(quasis, function (quasi, i) {
print(quasi);
if (i + 1 < len) {
self.push("${ ");
print(node.expressions[i]);
self.push(" }");
}
});
this._push("`");
};

View File

@@ -1,361 +0,0 @@
"use strict";
module.exports = function (ast, opts, code) {
var gen = new CodeGenerator(ast, opts, code);
return gen.generate();
};
module.exports.CodeGenerator = CodeGenerator;
var detectIndent = require("detect-indent");
var Whitespace = require("./whitespace");
var SourceMap = require("./source-map");
var Position = require("./position");
var Buffer = require("./buffer");
var extend = require("lodash/object/extend");
var merge = require("lodash/object/merge");
var each = require("lodash/collection/each");
var util = require("../util");
var n = require("./node");
var t = require("../types");
function CodeGenerator(ast, opts, code) {
opts = opts || {};
this.comments = ast.comments || [];
this.tokens = ast.tokens || [];
this.format = CodeGenerator.normalizeOptions(code, opts);
this.opts = opts;
this.ast = ast;
this.whitespace = new Whitespace(this.tokens, this.comments);
this.position = new Position;
this.map = new SourceMap(this.position, opts, code);
this.buffer = new Buffer(this.position, this.format);
}
each(Buffer.prototype, function (fn, key) {
CodeGenerator.prototype[key] = function () {
return fn.apply(this.buffer, arguments);
};
});
CodeGenerator.normalizeOptions = function (code, opts) {
var style = " ";
if (code) {
var indent = detectIndent(code).indent;
if (indent && indent !== " ") style = indent;
}
return merge({
parentheses: true,
comments: opts.comments == null || opts.comments,
compact: false,
concise: false,
indent: {
adjustMultilineComment: true,
style: style,
base: 0
}
}, opts.format || {});
};
CodeGenerator.generators = {
templateLiterals: require("./generators/template-literals"),
comprehensions: require("./generators/comprehensions"),
expressions: require("./generators/expressions"),
statements: require("./generators/statements"),
playground: require("./generators/playground"),
classes: require("./generators/classes"),
methods: require("./generators/methods"),
modules: require("./generators/modules"),
types: require("./generators/types"),
flow: require("./generators/flow"),
base: require("./generators/base"),
jsx: require("./generators/jsx")
};
each(CodeGenerator.generators, function (generator) {
extend(CodeGenerator.prototype, generator);
});
CodeGenerator.prototype.generate = function () {
var ast = this.ast;
this.print(ast);
var comments = [];
each(ast.comments, function (comment) {
if (!comment._displayed) comments.push(comment);
});
this._printComments(comments);
return {
map: this.map.get(),
code: this.buffer.get()
};
};
CodeGenerator.prototype.buildPrint = function (parent) {
var self = this;
var print = function (node, opts) {
return self.print(node, parent, opts);
};
print.sequence = function (nodes, opts) {
opts = opts || {};
opts.statement = true;
return self.printJoin(print, nodes, opts);
};
print.join = function (nodes, opts) {
return self.printJoin(print, nodes, opts);
};
print.list = function (items, opts) {
opts = opts || {};
var sep = opts.separator || ", ";
if (self.format.compact) sep = ",";
opts.separator = sep;
print.join(items, opts);
};
print.block = function (node) {
return self.printBlock(print, node);
};
print.indentOnComments = function (node) {
return self.printAndIndentOnComments(print, node);
};
return print;
};
CodeGenerator.prototype.print = function (node, parent, opts) {
if (!node) return "";
if (parent && parent._compact) {
node._compact = true;
}
var oldConcise = this.format.concise;
if (node._compact) {
this.format.concise = true;
}
var self = this;
opts = opts || {};
var newline = function (leading) {
if (!opts.statement && !n.isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace) {
// user node
if (leading) {
lines = self.whitespace.getNewlinesBefore(node);
} else {
lines = self.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
var needs = n.needsWhitespaceAfter;
if (leading) needs = n.needsWhitespaceBefore;
lines += needs(node, parent);
// generated nodes can't add starting file whitespace
if (!self.buffer.get()) lines = 0;
}
self.newline(lines);
};
if (this[node.type]) {
var needsNoLineTermParens = n.needsParensNoLineTerminator(node, parent);
var needsParens = needsNoLineTermParens || n.needsParens(node, parent);
if (needsParens) this.push("(");
if (needsNoLineTermParens) this.indent();
this.printLeadingComments(node, parent);
newline(true);
if (opts.before) opts.before();
this.map.mark(node, "start");
this[node.type](node, this.buildPrint(node), parent);
if (needsNoLineTermParens) {
this.newline();
this.dedent();
}
if (needsParens) this.push(")");
this.map.mark(node, "end");
if (opts.after) opts.after();
newline(false);
this.printTrailingComments(node, parent);
} else {
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
}
this.format.concise = oldConcise;
};
CodeGenerator.prototype.printJoin = function (print, nodes, opts) {
if (!nodes || !nodes.length) return;
opts = opts || {};
var self = this;
var len = nodes.length;
if (opts.indent) self.indent();
each(nodes, function (node, i) {
print(node, {
statement: opts.statement,
after: function () {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < len - 1) {
self.push(opts.separator);
}
}
});
});
if (opts.indent) self.dedent();
};
CodeGenerator.prototype.printAndIndentOnComments = function (print, node) {
var indent = !!node.leadingComments;
if (indent) this.indent();
print(node);
if (indent) this.dedent();
};
CodeGenerator.prototype.printBlock = function (print, node) {
if (t.isEmptyStatement(node)) {
this.semicolon();
} else {
this.push(" ");
print(node);
}
};
CodeGenerator.prototype.generateComment = function (comment) {
var val = comment.value;
if (comment.type === "Line") {
val = "//" + val;
} else {
val = "/*" + val + "*/";
}
return val;
};
CodeGenerator.prototype.printTrailingComments = function (node, parent) {
this._printComments(this.getComments("trailingComments", node, parent));
};
CodeGenerator.prototype.printLeadingComments = function (node, parent) {
this._printComments(this.getComments("leadingComments", node, parent));
};
CodeGenerator.prototype.getComments = function (key, node, parent) {
if (t.isExpressionStatement(parent)) {
return [];
}
var comments = [];
var nodes = [node];
var self = this;
if (t.isExpressionStatement(node)) {
nodes.push(node.argument);
}
each(nodes, function (node) {
comments = comments.concat(self._getComments(key, node));
});
return comments;
};
CodeGenerator.prototype._getComments = function (key, node) {
return (node && node[key]) || [];
};
CodeGenerator.prototype._printComments = function (comments) {
if (this.format.compact) return;
if (!this.format.comments) return;
if (!comments || !comments.length) return;
var self = this;
each(comments, function (comment) {
var skip = false;
// find the original comment in the ast and set it as displayed
each(self.ast.comments, function (origComment) {
if (origComment.start === comment.start) {
// comment has already been output
if (origComment._displayed) skip = true;
origComment._displayed = true;
return false;
}
});
if (skip) return;
// whitespace before
self.newline(self.whitespace.getNewlinesBefore(comment));
var column = self.position.column;
var val = self.generateComment(comment);
if (column && !self.isLast(["\n", " ", "[", "{"])) {
self._push(" ");
column++;
}
//
if (comment.type === "Block" && self.format.indent.adjustMultilineComment) {
var offset = comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
var indent = Math.max(self.indentSize(), column);
val = val.replace(/\n/g, "\n" + util.repeat(indent));
}
if (column === 0) {
val = self.getIndent() + val;
}
//
self._push(val);
// whitespace after
self.newline(self.whitespace.getNewlinesAfter(comment));
});
};

View File

@@ -1,112 +0,0 @@
"use strict";
module.exports = Node;
var whitespace = require("./whitespace");
var parens = require("./parentheses");
var t = require("../../types");
var each = require("lodash/collection/each");
var some = require("lodash/collection/some");
var find = function (obj, node, parent) {
if (!obj) return;
var result;
var types = Object.keys(obj);
for (var i = 0; i < types.length; i++) {
var type = types[i];
if (t.is(type, node)) {
var fn = obj[type];
result = fn(node, parent);
if (result != null) break;
}
}
return result;
};
function Node(node, parent) {
this.parent = parent;
this.node = node;
}
Node.isUserWhitespacable = function (node) {
return t.isUserWhitespacable(node);
};
Node.needsWhitespace = function (node, parent, type) {
if (!node) return 0;
if (t.isExpressionStatement(node)) {
node = node.expression;
}
var lines = find(whitespace[type].nodes, node, parent);
if (lines) return lines;
each(find(whitespace[type].list, node, parent), function (expr) {
lines = Node.needsWhitespace(expr, node, type);
if (lines) return false;
});
return lines || 0;
};
Node.needsWhitespaceBefore = function (node, parent) {
return Node.needsWhitespace(node, parent, "before");
};
Node.needsWhitespaceAfter = function (node, parent) {
return Node.needsWhitespace(node, parent, "after");
};
Node.needsParens = function (node, parent) {
if (!parent) return false;
if (t.isNewExpression(parent) && parent.callee === node) {
if (t.isCallExpression(node)) return true;
var hasCall = some(node, function (val) {
return t.isCallExpression(val);
});
if (hasCall) return true;
}
return find(parens, node, parent);
};
Node.needsParensNoLineTerminator = function (node, parent) {
if (!parent) return false;
// no comments
if (!node.leadingComments || !node.leadingComments.length) {
return false;
}
if (t.isYieldExpression(parent) || t.isAwaitExpression(parent)) {
return true;
}
if (t.isContinueStatement(parent) || t.isBreakStatement(parent) ||
t.isReturnStatement(parent) || t.isThrowStatement(parent)) {
return true;
}
return false;
};
each(Node, function (fn, key) {
Node.prototype[key] = function () {
// Avoid leaking arguments to prevent deoptimization
var args = new Array(arguments.length + 2);
args[0] = this.node;
args[1] = this.parent;
for (var i = 0; i < args.length; i++) {
args[i + 2] = arguments[i];
}
return Node[key].apply(null, args);
};
});

View File

@@ -1,84 +0,0 @@
"use strict";
var t = require("../../types");
var each = require("lodash/collection/each");
var map = require("lodash/collection/map");
var isNumber = require("lodash/lang/isNumber");
exports.before = {
nodes: {
Property: function (node, parent) {
if (parent.properties[0] === node) {
return 1;
}
},
SpreadProperty: function (node, parent) {
return exports.before.nodes.Property(node, parent);
},
SwitchCase: function (node, parent) {
if (parent.cases[0] === node) {
return 1;
}
},
CallExpression: function (node) {
if (t.isFunction(node.callee)) {
return 1;
}
}
}
};
exports.after = {
nodes: {
LogicalExpression: function (node) {
return t.isFunction(node.left) || t.isFunction(node.right);
},
AssignmentExpression: function (node) {
if (t.isFunction(node.right)) {
return 1;
}
}
},
list: {
VariableDeclaration: function (node) {
return map(node.declarations, "init");
},
ArrayExpression: function (node) {
return node.elements;
},
ObjectExpression: function (node) {
return node.properties;
}
}
};
each({
Function: 1,
Class: 1,
For: 1,
ArrayExpression: { after: 1 },
ObjectExpression: { after: 1 },
SwitchStatement: 1,
IfStatement: { before: 1 },
CallExpression: { after: 1 },
Literal: { after: 1 }
}, function (amounts, type) {
if (isNumber(amounts)) {
amounts = { after: amounts, before: amounts };
}
each([type].concat(t.FLIPPED_ALIAS_KEYS[type] || []), function (type) {
each(amounts, function (amount, key) {
exports[key].nodes[type] = function () {
return amount;
};
});
});
});

View File

@@ -1,29 +0,0 @@
"use strict";
module.exports = Position;
function Position() {
this.line = 1;
this.column = 0;
}
Position.prototype.push = function (str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line++;
this.column = 0;
} else {
this.column++;
}
}
};
Position.prototype.unshift = function (str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line--;
} else {
this.column--;
}
}
};

View File

@@ -1,56 +0,0 @@
"use strict";
module.exports = SourceMap;
var sourceMap = require("source-map");
var t = require("../types");
function SourceMap(position, opts, code) {
this.position = position;
this.opts = opts;
if (opts.sourceMap) {
this.map = new sourceMap.SourceMapGenerator({
file: opts.sourceMapName,
sourceRoot: opts.sourceRoot
});
this.map.setSourceContent(opts.sourceFileName, code);
} else {
this.map = null;
}
}
SourceMap.prototype.get = function () {
var map = this.map;
if (map) {
return map.toJSON();
} else {
return map;
}
};
SourceMap.prototype.mark = function (node, type) {
var loc = node.loc;
if (!loc) return; // no location info
var map = this.map;
if (!map) return; // no source map
if (t.isProgram(node) || t.isFile(node)) return; // illegal mapping nodes
var position = this.position;
var generated = {
line: position.line,
column: position.column
};
var original = loc[type];
map.addMapping({
source: this.opts.sourceFileName,
generated: generated,
original: original
});
};

View File

@@ -1,111 +0,0 @@
"use strict";
module.exports = Whitespace;
var sortBy = require("lodash/collection/sortBy");
/**
* Returns `i`th number from `base`, continuing from 0 when `max` is reached.
* Useful for shifting `for` loop by a fixed number but going over all items.
*
* @param {Number} i Current index in the loop
* @param {Number} base Start index for which to return 0
* @param {Number} max Array length
* @returns {Number} shiftedIndex
*/
function getLookupIndex(i, base, max) {
i += base;
if (i >= max)
i -= max;
return i;
}
function Whitespace(tokens, comments) {
this.tokens = sortBy(tokens.concat(comments), "start");
this.used = {};
// Profiling this code shows that while generator passes over it, indexes
// returned by `getNewlinesBefore` and `getNewlinesAfter` are always increasing.
// We use this implementation detail for an optimization: instead of always
// starting to look from `this.tokens[0]`, we will start `for` loops from the
// previous successful match. We will enumerate all tokens—but the common
// case will be much faster.
this._lastFoundIndex = 0;
}
Whitespace.prototype.getNewlinesBefore = function (node) {
var startToken;
var endToken;
var tokens = this.tokens;
var token;
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
// this is the token this node starts with
if (node.start === token.start) {
startToken = tokens[i - 1];
endToken = token;
this._lastFoundIndex = i;
break;
}
}
return this.getNewlinesBetween(startToken, endToken);
};
Whitespace.prototype.getNewlinesAfter = function (node) {
var startToken;
var endToken;
var tokens = this.tokens;
var token;
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
// this is the token this node ends with
if (node.end === token.end) {
startToken = token;
endToken = tokens[i + 1];
this._lastFoundIndex = i;
break;
}
}
if (endToken.type.type === "eof") {
return 1;
} else {
var lines = this.getNewlinesBetween(startToken, endToken);
if (node.type === "Line" && !lines) {
// line comment
return 1;
} else {
return lines;
}
}
};
Whitespace.prototype.getNewlinesBetween = function (startToken, endToken) {
var start = startToken ? startToken.loc.end.line : 1;
var end = endToken.loc.start.line;
var lines = 0;
for (var line = start; line < end; line++) {
if (typeof this.used[line] === "undefined") {
this.used[line] = true;
lines++;
}
}
return lines;
};

View File

@@ -1,12 +0,0 @@
"use strict";
module.exports = function cloneDeep(obj) {
var obj2 = {};
if (!obj) return obj2;
for (var key in obj) {
obj2[key] = obj[key];
}
return obj2;
};

View File

@@ -1,79 +0,0 @@
// syntax highlighting based on https://github.com/dominictarr/ansi-highlight by the fantastic Dominic Tarr
var supportsColor = require("supports-color");
var tokenize = require("js-tokenizer");
var chalk = require("chalk");
var util = require("../util");
var defs = {
string1: "red",
string2: "red",
punct: ["white", "bold"],
curly: "green",
parens: ["blue", "bold"],
square: ["yellow"],
name: "white",
keyword: ["cyan"],
number: "magenta",
regexp: "magenta",
comment1: "grey",
comment2: "grey"
};
var highlight = function (text) {
var colorize = function (str, col) {
if (!col) return str;
if (Array.isArray(col)) {
col.forEach(function (col) {
str = chalk[col](str);
});
} else {
str = chalk[col](str);
}
return str;
};
return tokenize(text, true).map(function (str) {
var type = tokenize.type(str);
return colorize(str, defs[type]);
}).join("");
};
module.exports = function (lines, lineNumber, colNumber) {
colNumber = Math.max(colNumber, 0);
if (supportsColor) {
lines = highlight(lines);
}
lines = lines.split(/\r\n|[\n\r\u2028\u2029]/);
var start = Math.max(lineNumber - 3, 0);
var end = Math.min(lines.length, lineNumber + 3);
var width = (end + "").length;
if (!lineNumber && !colNumber) {
start = 0;
end = lines.length;
}
return "\n" + lines.slice(start, end).map(function (line, i) {
var curr = i + start + 1;
var gutter = curr === lineNumber ? "> " : " ";
var sep = curr + util.repeat(width + 1);
gutter += sep + "| ";
var str = gutter + line;
if (colNumber && curr === lineNumber) {
str += "\n";
str += util.repeat(gutter.length - 2);
str += "|" + util.repeat(colNumber) + "^";
}
return str;
}).join("\n");
};

View File

@@ -1,38 +0,0 @@
// taken from stackoverflow, it's crap i know.
module.exports = function (a, b) {
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
var matrix = [];
// increment along the first column of each row
var i;
for (i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
// increment each column in the first row
var j;
for (j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
// Fill in the rest of the matrix
for (i = 1; i <= b.length; i++) {
for (j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) == a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1, // substitution
Math.min(
matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j] + 1) // deletion
);
}
}
}
return matrix[b.length][a.length];
};

View File

@@ -1,5 +0,0 @@
"use strict";
module.exports = function () {
return Object.create(null);
};

View File

@@ -1,17 +0,0 @@
"use strict";
/**
* A trick from Bluebird to force V8 to use fast properties for an object.
* Read more: http://stackoverflow.com/questions/24987896/
*
* Use %HasFastProperties(obj) and --allow-natives-syntax to check whether
* a particular object already has fast properties.
*/
module.exports = function toFastProperties(obj) {
/*jshint -W027*/
function f() {}
f.prototype = obj;
return f;
eval(obj);
};

View File

@@ -1,9 +0,0 @@
"use strict";
if (global._6to5Polyfill) {
throw new Error("only one instance of 6to5/polyfill is allowed");
}
global._6to5Polyfill = true;
require("core-js/shim");
require("regenerator-6to5/runtime");

View File

@@ -1,448 +0,0 @@
"use strict";
module.exports = File;
var SHEBANG_REGEX = /^\#\!.*/;
var isFunction = require("lodash/lang/isFunction");
var transform = require("./index");
var generate = require("../generation");
var defaults = require("lodash/object/defaults");
var includes = require("lodash/collection/includes");
var clone = require("../helpers/clone");
var parse = require("../helpers/parse");
var Scope = require("../traversal/scope");
var util = require("../util");
var path = require("path");
var each = require("lodash/collection/each");
var t = require("../types");
function File(opts) {
this.dynamicImportedNoDefault = [];
this.dynamicImportIds = {};
this.dynamicImported = [];
this.dynamicImports = [];
this.dynamicData = {};
this.data = {};
this.lastStatements = [];
this.opts = this.normalizeOptions(opts);
this.ast = {};
this.buildTransformers();
}
File.helpers = [
"inherits",
"defaults",
"prototype-properties",
"apply-constructor",
"tagged-template-literal",
"tagged-template-literal-loose",
"interop-require",
"to-array",
"to-consumable-array",
"sliced-to-array",
"object-without-properties",
"has-own",
"slice",
"bind",
"define-property",
"async-to-generator",
"interop-require-wildcard",
"typeof",
"extends",
"get",
"set",
"class-call-check",
"object-destructuring-empty",
"temporal-undefined",
"temporal-assert-defined",
"tail-call"
];
File.validOptions = [
"filename",
"filenameRelative",
"blacklist",
"whitelist",
"loose",
"optional",
"modules",
"sourceMap",
"sourceMapName",
"sourceFileName",
"sourceRoot",
"moduleRoot",
"moduleIds",
"comments",
"reactCompat",
"keepModuleIdExtensions",
"code",
"ast",
"format",
"playground",
"experimental",
"resolveModuleSource",
"runtime",
// these are used by plugins
"ignore",
"only",
"extensions",
"accept"
];
File.prototype.normalizeOptions = function (opts) {
opts = clone(opts);
for (var key in opts) {
if (key[0] !== "_" && File.validOptions.indexOf(key) < 0) {
throw new ReferenceError("Unknown option: " + key);
}
}
defaults(opts, {
keepModuleIdExtensions: false,
resolveModuleSource: null,
experimental: false,
reactCompat: false,
playground: false,
whitespace: true,
moduleIds: false,
blacklist: [],
whitelist: [],
sourceMap: false,
optional: [],
comments: true,
filename: "unknown",
modules: "common",
runtime: false,
loose: [],
code: true,
ast: true
});
// normalize windows path separators to unix
opts.filename = util.normalisePathSeparator(opts.filename);
if (opts.sourceRoot) {
opts.sourceRoot = util.normalisePathSeparator(opts.sourceRoot);
}
opts.basename = path.basename(opts.filename, path.extname(opts.filename));
opts.blacklist = util.arrayify(opts.blacklist);
opts.whitelist = util.arrayify(opts.whitelist);
opts.optional = util.arrayify(opts.optional);
opts.loose = util.arrayify(opts.loose);
if (includes(opts.loose, "all") || includes(opts.loose, true)) {
opts.loose = Object.keys(transform.transformers);
}
defaults(opts, {
moduleRoot: opts.sourceRoot
});
defaults(opts, {
sourceRoot: opts.moduleRoot
});
defaults(opts, {
filenameRelative: opts.filename
});
defaults(opts, {
sourceFileName: opts.filenameRelative,
sourceMapName: opts.filenameRelative
});
if (opts.playground) {
opts.experimental = true;
}
if (opts.runtime) {
this.set("runtimeIdentifier", t.identifier("to5Runtime"));
}
opts.blacklist = transform._ensureTransformerNames("blacklist", opts.blacklist);
opts.whitelist = transform._ensureTransformerNames("whitelist", opts.whitelist);
opts.optional = transform._ensureTransformerNames("optional", opts.optional);
opts.loose = transform._ensureTransformerNames("loose", opts.loose);
if (opts.reactCompat) {
opts.optional.push("reactCompat");
console.error("The reactCompat option has been moved into the optional transformer " +
"`reactCompat` - backwards compatibility will be removed in v4.0.0");
}
var ensureEnabled = function (key) {
var namespace = transform.transformerNamespaces[key];
if (namespace === "es7") opts.experimental = true;
if (namespace === "playground") opts.playground = true;
};
each(opts.whitelist, ensureEnabled);
each(opts.optional, ensureEnabled);
return opts;
};
File.prototype.isLoose = function (key) {
return includes(this.opts.loose, key);
};
File.prototype.buildTransformers = function () {
var file = this;
var transformers = {};
var secondaryStack = [];
var stack = [];
each(transform.transformers, function (transformer, key) {
var pass = transformers[key] = transformer.buildPass(file);
if (pass.canRun(file)) {
stack.push(pass);
if (transformer.secondPass) {
secondaryStack.push(pass);
}
if (transformer.manipulateOptions) {
transformer.manipulateOptions(file.opts, file);
}
}
});
this.transformerStack = stack.concat(secondaryStack);
this.transformers = transformers;
};
File.prototype.debug = function (msg) {
var parts = this.opts.filename;
if (msg) parts += ": " + msg;
util.debug(parts);
};
File.prototype.getModuleFormatter = function (type) {
var ModuleFormatter = isFunction(type) ? type : transform.moduleFormatters[type];
if (!ModuleFormatter) {
var loc = util.resolve(type);
if (loc) ModuleFormatter = require(loc);
}
if (!ModuleFormatter) {
throw new ReferenceError("Unknown module formatter type " + JSON.stringify(type));
}
return new ModuleFormatter(this);
};
File.prototype.parseShebang = function (code) {
var shebangMatch = code.match(SHEBANG_REGEX);
if (shebangMatch) {
this.shebang = shebangMatch[0];
// remove shebang
code = code.replace(SHEBANG_REGEX, "");
}
return code;
};
File.prototype.set = function (key, val) {
return this.data[key] = val;
};
File.prototype.setDynamic = function (key, fn) {
this.dynamicData[key] = fn;
};
File.prototype.get = function (key) {
var data = this.data[key];
if (data) {
return data;
} else {
var dynamic = this.dynamicData[key];
if (dynamic) {
return this.set(key, dynamic());
}
}
};
File.prototype.addImport = function (source, name, noDefault) {
name = name || source;
var id = this.dynamicImportIds[name];
if (!id) {
id = this.dynamicImportIds[name] = this.scope.generateUidIdentifier(name);
var specifiers = [t.importSpecifier(t.identifier("default"), id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
this.dynamicImported.push(declar);
if (noDefault) this.dynamicImportedNoDefault.push(declar);
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports);
}
return id;
};
File.prototype.isConsequenceExpressionStatement = function (node) {
return t.isExpressionStatement(node) && this.lastStatements.indexOf(node) >= 0;
};
File.prototype.addHelper = function (name) {
if (!includes(File.helpers, name)) {
throw new ReferenceError("Unknown helper " + name);
}
var program = this.ast.program;
var declar = program._declarations && program._declarations[name];
if (declar) return declar.id;
var runtime = this.get("runtimeIdentifier");
if (runtime) {
name = t.identifier(t.toIdentifier(name));
return t.memberExpression(runtime, name);
} else {
var ref = util.template(name);
ref._compact = true;
var uid = this.scope.generateUidIdentifier(name);
this.scope.push({
key: name,
id: uid,
init: ref
});
return uid;
}
};
File.prototype.logDeopt = function () {
// todo, (node, msg)
};
File.prototype.errorWithNode = function (node, msg, Error) {
Error = Error || SyntaxError;
var loc = node.loc.start;
var err = new Error("Line " + loc.line + ": " + msg);
err.loc = loc;
return err;
};
File.prototype.addCode = function (code) {
code = (code || "") + "";
this.code = code;
return this.parseShebang(code);
};
File.prototype.parse = function (code) {
var self = this;
code = this.addCode(code);
var opts = this.opts;
opts.allowImportExportEverywhere = this.isLoose("es6.modules");
//opts.strictMode = this.transformers.useStrict.canRun();
return parse(opts, code, function (tree) {
self.transform(tree);
return self.generate();
});
};
File.prototype.transform = function (ast) {
this.debug();
this.ast = ast;
this.lastStatements = t.getLastStatements(ast.program);
this.scope = new Scope(ast.program, ast, null, this);
var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
if (modFormatter.init && this.transformers["es6.modules"].canRun()) {
modFormatter.init();
}
this.checkNode(ast);
this.call("pre");
each(this.transformerStack, function (pass) {
pass.transform();
});
this.call("post");
};
File.prototype.call = function (key) {
var stack = this.transformerStack;
for (var i = 0; i < stack.length; i++) {
var transformer = stack[i].transformer;
if (transformer[key]) {
transformer[key](this);
}
}
};
var checkTransformerVisitor = {
enter: function (node, parent, scope, state) {
checkNode(state.stack, node, scope);
}
};
var checkNode = function (stack, node, scope) {
each(stack, function (pass) {
if (pass.shouldRun) return;
pass.checkNode(node, scope);
});
};
File.prototype.checkNode = function (node, scope) {
var stack = this.transformerStack;
scope = scope || this.scope;
checkNode(stack, node, scope);
scope.traverse(node, checkTransformerVisitor, {
stack: stack
});
};
File.prototype.generate = function () {
var opts = this.opts;
var ast = this.ast;
var result = {
code: "",
map: null,
ast: null
};
if (opts.ast) result.ast = ast;
if (!opts.code) return result;
var _result = generate(ast, opts, this.code);
result.code = _result.code;
result.map = _result.map;
if (this.shebang) {
// add back shebang
result.code = this.shebang + "\n" + result.code;
}
if (opts.sourceMap === "inline") {
result.code += "\n" + util.sourceMapToComment(result.map);
result.map = null;
}
return result;
};

View File

@@ -1,73 +0,0 @@
var cloneDeep = require("lodash/lang/cloneDeep");
var traverse = require("../../traversal");
var clone = require("lodash/lang/clone");
var each = require("lodash/collection/each");
var has = require("lodash/object/has");
var t = require("../../types");
exports.push = function (mutatorMap, key, kind, computed, value) {
var alias;
if (t.isIdentifier(key)) {
alias = key.name;
if (computed) alias = "computed:" + alias;
} else if (t.isLiteral(key)) {
alias = String(key.value);
} else {
alias = JSON.stringify(traverse.removeProperties(cloneDeep(key)));
}
var map;
if (has(mutatorMap, alias)) {
map = mutatorMap[alias];
} else {
map = {};
}
mutatorMap[alias] = map;
map._key = key;
if (computed) {
map._computed = true;
}
map[kind] = value;
};
exports.build = function (mutatorMap) {
var objExpr = t.objectExpression([]);
each(mutatorMap, function (map) {
var mapNode = t.objectExpression([]);
var propNode = t.property("init", map._key, mapNode, map._computed);
if (!map.get && !map.set) {
map.writable = t.literal(true);
}
if (map.enumerable === false) {
delete map.enumerable;
} else {
map.enumerable = t.literal(true);
}
map.configurable = t.literal(true);
each(map, function (node, key) {
if (key[0] === "_") return;
node = clone(node);
var inheritNode = node;
if (t.isMethodDefinition(node)) node = node.value;
var prop = t.property("init", t.identifier(key), node);
t.inheritsComments(prop, inheritNode);
t.removeComments(inheritNode);
mapNode.properties.push(prop);
});
objExpr.properties.push(propNode);
});
return objExpr;
};

View File

@@ -1,53 +0,0 @@
"use strict";
var util = require("../../util");
var t = require("../../types");
var visitor = {
enter: function (node, parent, scope, state) {
// check if this node is an identifier that matches the same as our function id
if (!t.isIdentifier(node, { name: state.id })) return;
// check if this node is the one referenced
if (!t.isReferenced(node, parent)) return;
// check that we don't have a local variable declared as that removes the need
// for the wrapper
var localDeclar = scope.getBindingIdentifier(state.id);
if (localDeclar !== state.outerDeclar) return;
state.selfReference = true;
this.stop();
}
};
exports.property = function (node, file, scope) {
var key = t.toComputedKey(node, node.key);
if (!t.isLiteral(key)) return node; // we can't set a function id with this
var id = t.toIdentifier(key.value);
key = t.identifier(id);
var state = {
id: id,
selfReference: false,
outerDeclar: scope.getBindingIdentifier(id),
};
scope.traverse(node, visitor, state);
var method = node.value;
if (state.selfReference) {
var templateName = "property-method-assignment-wrapper";
if (method.generator) templateName += "-generator";
node.value = util.template(templateName, {
FUNCTION: method,
FUNCTION_ID: key,
FUNCTION_KEY: scope.generateUidIdentifier(id),
WRAPPER_KEY: scope.generateUidIdentifier(id + "Wrapper")
});
} else {
method.id = key;
}
};

View File

@@ -1,40 +0,0 @@
"use strict";
var t = require("../../types");
var visitor = {
enter: function (node) {
if (t.isFunction(node)) this.skip();
if (t.isAwaitExpression(node)) {
node.type = "YieldExpression";
if (node.all) {
// await* foo; -> yield Promise.all(foo);
node.all = false;
node.argument = t.callExpression(t.memberExpression(t.identifier("Promise"), t.identifier("all")), [node.argument]);
}
}
}
};
module.exports = function (node, callId, scope) {
node.async = false;
node.generator = true;
scope.traverse(node, visitor);
var call = t.callExpression(callId, [node]);
var id = node.id;
delete node.id;
if (t.isFunctionDeclaration(node)) {
var declar = t.variableDeclaration("let", [
t.variableDeclarator(id, call)
]);
declar._blockHoist = true;
return declar;
} else {
return call;
}
};

View File

@@ -1,303 +0,0 @@
"use strict";
module.exports = ReplaceSupers;
var messages = require("../../messages");
var t = require("../../types");
/**
* Description
*
* @param {Object} opts
* @param {Boolean} [inClass]
*/
function ReplaceSupers(opts, inClass) {
this.topLevelThisReference = opts.topLevelThisReference;
this.methodNode = opts.methodNode;
this.className = opts.className;
this.superName = opts.superName;
this.isStatic = opts.isStatic;
this.hasSuper = false;
this.inClass = inClass;
this.isLoose = opts.isLoose;
this.scope = opts.scope;
this.file = opts.file;
}
/**
* Sets a super class value of the named property.
*
* @example
*
* _set(Object.getPrototypeOf(CLASS.prototype), "METHOD", "VALUE", this)
*
* @param {Node} property
* @param {Node} value
* @param {Boolean} isComputed
* @param {Node} thisExpression
*
* @returns {Node}
*/
ReplaceSupers.prototype.setSuperProperty = function (property, value, isComputed, thisExpression) {
return t.callExpression(
this.file.addHelper("set"),
[
t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
[
this.isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
]
),
isComputed ? property : t.literal(property.name),
value,
thisExpression
]
);
};
/**
* Gets a node representing the super class value of the named property.
*
* @example
*
* _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
*
* @param {Node} property
* @param {Boolean} isComputed
* @param {Node} thisExpression
*
* @returns {Node}
*/
ReplaceSupers.prototype.getSuperProperty = function (property, isComputed, thisExpression) {
return t.callExpression(
this.file.addHelper("get"),
[
t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
[
this.isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
]
),
isComputed ? property : t.literal(property.name),
thisExpression
]
);
};
/**
* Description
*/
ReplaceSupers.prototype.replace = function () {
this.traverseLevel(this.methodNode.value, true);
};
var visitor = {
enter: function (node, parent, scope, state) {
var topLevel = state.topLevel;
var self = state.self;
if (t.isFunction(node) && !t.isArrowFunctionExpression(node)) {
// we need to call traverseLevel again so we're context aware
self.traverseLevel(node, false);
return this.skip();
}
if (t.isProperty(node, { method: true }) || t.isMethodDefinition(node)) {
// break on object methods
return this.skip();
}
var getThisReference = topLevel ?
// top level so `this` is the instance
t.thisExpression :
// not in the top level so we need to create a reference
self.getThisReference.bind(self);
var callback = self.specHandle;
if (self.isLoose) callback = self.looseHandle;
return callback.call(self, getThisReference, node, parent);
}
};
/**
* Description
*
* @param {Object} node
* @param {Boolean} topLevel
*/
ReplaceSupers.prototype.traverseLevel = function (node, topLevel) {
var state = { self: this, topLevel: topLevel };
this.scope.traverse(node, visitor, state);
};
/**
* Description
*/
ReplaceSupers.prototype.getThisReference = function () {
if (this.topLevelThisReference) {
return this.topLevelThisReference;
} else {
var ref = this.topLevelThisReference = this.scope.generateUidIdentifier("this");
this.methodNode.value.body.body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(this.topLevelThisReference, t.thisExpression())
]));
return ref;
}
};
/**
* Description
*
* @param {Object} node
* @param {Object} id
* @param {Object} parent
* @returns {Object}
*/
ReplaceSupers.prototype.getLooseSuperProperty = function (id, parent) {
var methodNode = this.methodNode;
var methodName = methodNode.key;
var superName = this.superName || t.identifier("Function");
if (parent.property === id) {
return;
} else if (t.isCallExpression(parent, { callee: id })) {
// super(); -> ClassName.prototype.MethodName.call(this);
parent.arguments.unshift(t.thisExpression());
if (methodName.name === "constructor") {
// constructor() { super(); }
return t.memberExpression(superName, t.identifier("call"));
} else {
id = superName;
// foo() { super(); }
if (!methodNode.static) {
id = t.memberExpression(id, t.identifier("prototype"));
}
id = t.memberExpression(id, methodName, methodNode.computed);
return t.memberExpression(id, t.identifier("call"));
}
} else if (t.isMemberExpression(parent) && !methodNode.static) {
// super.test -> ClassName.prototype.test
return t.memberExpression(superName, t.identifier("prototype"));
} else {
return superName;
}
};
/**
* Description
*
* @param {Function} getThisReference
* @param {Object} node
* @param {Object} parent
*/
ReplaceSupers.prototype.looseHandle = function (getThisReference, node, parent) {
if (t.isIdentifier(node, { name: "super" })) {
this.hasSuper = true;
return this.getLooseSuperProperty(node, parent);
} else if (t.isCallExpression(node)) {
var callee = node.callee;
if (!t.isMemberExpression(callee)) return;
if (callee.object.name !== "super") return;
// super.test(); -> ClassName.prototype.MethodName.call(this);
this.hasSuper = true;
t.appendToMemberExpression(callee, t.identifier("call"));
node.arguments.unshift(getThisReference());
}
};
/**
* Description
*
* @param {Function} getThisReference
* @param {Object} node
* @param {Object} parent
*/
ReplaceSupers.prototype.specHandle = function (getThisReference, node, parent) {
var methodNode = this.methodNode;
var property;
var computed;
var args;
var thisReference;
if (isIllegalBareSuper(node, parent)) {
throw this.file.errorWithNode(node, messages.get("classesIllegalBareSuper"));
}
if (t.isCallExpression(node)) {
var callee = node.callee;
if (isSuper(callee, node)) {
// super(); -> _get(Object.getPrototypeOf(ClassName), "MethodName", this).call(this);
property = methodNode.key;
computed = methodNode.computed;
args = node.arguments;
// bare `super` call is illegal inside non-constructors
// - https://esdiscuss.org/topic/super-call-in-methods
// - https://twitter.com/wycats/status/544553184396836864
if (methodNode.key.name !== "constructor" || !this.inClass) {
var methodName = methodNode.key.name || "METHOD_NAME";
throw this.file.errorWithNode(node, messages.get("classesIllegalSuperCall", methodName));
}
} else if (t.isMemberExpression(callee) && isSuper(callee.object, callee)) {
// super.test(); -> _get(Object.getPrototypeOf(ClassName.prototype), "test", this).call(this);
property = callee.property;
computed = callee.computed;
args = node.arguments;
}
} else if (t.isMemberExpression(node) && isSuper(node.object, node)) {
// super.name; -> _get(Object.getPrototypeOf(ClassName.prototype), "name", this);
property = node.property;
computed = node.computed;
} else if (t.isAssignmentExpression(node) && isSuper(node.left.object, node.left) && methodNode.kind === "set") {
// super.name = "val"; -> _set(Object.getPrototypeOf(ClassName.prototype), "name", this);
this.hasSuper = true;
return this.setSuperProperty(node.left.property, node.right, node.left.computed, getThisReference());
}
if (!property) return;
this.hasSuper = true;
thisReference = getThisReference();
var superProperty = this.getSuperProperty(property, computed, thisReference);
if (args) {
if (args.length === 1 && t.isSpreadElement(args[0])) {
// super(...arguments);
return t.callExpression(
t.memberExpression(superProperty, t.identifier("apply")),
[thisReference, args[0].argument]
);
} else {
return t.callExpression(
t.memberExpression(superProperty, t.identifier("call")),
[thisReference].concat(args)
);
}
} else {
return superProperty;
}
};
var isIllegalBareSuper = function (node, parent) {
if (!isSuper(node, parent)) return false;
if (t.isMemberExpression(parent, { computed: false })) return false;
if (t.isCallExpression(parent, { callee: node })) return false;
return true;
};
var isSuper = function (node, parent) {
return t.isIdentifier(node, { name: "super" }) && t.isReferenced(node, parent);
};

View File

@@ -1,293 +0,0 @@
"use strict";
module.exports = DefaultFormatter;
var messages = require("../../messages");
var extend = require("lodash/object/extend");
var object = require("../../helpers/object");
var util = require("../../util");
var t = require("../../types");
function DefaultFormatter(file) {
this.scope = file.scope;
this.file = file;
this.ids = object();
this.hasNonDefaultExports = false;
this.hasLocalExports = false;
this.hasLocalImports = false;
this.localImportOccurences = object();
this.localExports = object();
this.localImports = object();
this.getLocalExports();
this.getLocalImports();
this.remapAssignments();
}
DefaultFormatter.prototype.doDefaultExportInterop = function (node) {
return node.default && !this.noInteropRequireExport && !this.hasNonDefaultExports;
};
DefaultFormatter.prototype.bumpImportOccurences = function (node) {
var source = node.source.value;
var occurs = this.localImportOccurences;
occurs[source] = occurs[source] || 0;
occurs[source] += node.specifiers.length;
};
var exportsVisitor = {
enter: function (node, parent, scope, formatter) {
var declar = node && node.declaration;
if (t.isExportDeclaration(node)) {
formatter.hasLocalImports = true;
if (declar && t.isStatement(declar)) {
extend(formatter.localExports, t.getBindingIdentifiers(declar));
}
if (!node.default) {
formatter.hasNonDefaultExports = true;
}
if (node.source) {
formatter.bumpImportOccurences(node);
}
}
}
};
DefaultFormatter.prototype.getLocalExports = function () {
this.file.scope.traverse(this.file.ast, exportsVisitor, this);
};
var importsVisitor = {
enter: function (node, parent, scope, formatter) {
if (t.isImportDeclaration(node)) {
formatter.hasLocalImports = true;
extend(formatter.localImports, t.getBindingIdentifiers(node));
formatter.bumpImportOccurences(node);
}
}
};
DefaultFormatter.prototype.getLocalImports = function () {
this.file.scope.traverse(this.file.ast, importsVisitor, this);
};
var remapVisitor = {
enter: function (node, parent, scope, formatter) {
if (t.isUpdateExpression(node) && formatter.isLocalReference(node.argument, scope)) {
this.skip();
// expand to long file assignment expression
var assign = t.assignmentExpression(node.operator[0] + "=", node.argument, t.literal(1));
// remap this assignment expression
var remapped = formatter.remapExportAssignment(assign);
// we don't need to change the result
if (t.isExpressionStatement(parent) || node.prefix) {
return remapped;
}
var nodes = [];
nodes.push(remapped);
var operator;
if (node.operator === "--") {
operator = "+";
} else { // "++"
operator = "-";
}
nodes.push(t.binaryExpression(operator, node.argument, t.literal(1)));
return t.sequenceExpression(nodes);
}
if (t.isAssignmentExpression(node) && formatter.isLocalReference(node.left, scope)) {
this.skip();
return formatter.remapExportAssignment(node);
}
}
};
DefaultFormatter.prototype.remapAssignments = function () {
if (this.hasLocalImports) {
this.file.scope.traverse(this.file.ast, remapVisitor, this);
}
};
DefaultFormatter.prototype.isLocalReference = function (node) {
var localImports = this.localImports;
return t.isIdentifier(node) && localImports[node.name] && localImports[node.name] !== node;
};
DefaultFormatter.prototype.remapExportAssignment = function (node) {
return t.assignmentExpression(
"=",
node.left,
t.assignmentExpression(
node.operator,
t.memberExpression(t.identifier("exports"), node.left),
node.right
)
);
};
DefaultFormatter.prototype.isLocalReference = function (node, scope) {
var localExports = this.localExports;
var name = node.name;
return t.isIdentifier(node) && localExports[name] && localExports[name] === scope.getBindingIdentifier(name);
};
DefaultFormatter.prototype.getModuleName = function () {
var opts = this.file.opts;
var filenameRelative = opts.filenameRelative;
var moduleName = "";
if (opts.moduleRoot) {
moduleName = opts.moduleRoot + "/";
}
if (!opts.filenameRelative) {
return moduleName + opts.filename.replace(/^\//, "");
}
if (opts.sourceRoot) {
// remove sourceRoot from filename
var sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?");
filenameRelative = filenameRelative.replace(sourceRootRegEx, "");
}
if (!opts.keepModuleIdExtensions) {
// remove extension
filenameRelative = filenameRelative.replace(/\.(\w*?)$/, "");
}
moduleName += filenameRelative;
// normalize path separators
moduleName = moduleName.replace(/\\/g, "/");
return moduleName;
};
DefaultFormatter.prototype._pushStatement = function (ref, nodes) {
if (t.isClass(ref) || t.isFunction(ref)) {
if (ref.id) {
nodes.push(t.toStatement(ref));
ref = ref.id;
}
}
return ref;
};
DefaultFormatter.prototype._hoistExport = function (declar, assign, priority) {
if (t.isFunctionDeclaration(declar)) {
assign._blockHoist = priority || 2;
}
return assign;
};
DefaultFormatter.prototype.getExternalReference = function (node, nodes) {
var ids = this.ids;
var id = node.source.value;
if (ids[id]) {
return ids[id];
} else {
return this.ids[id] = this._getExternalReference(node, nodes);
}
};
DefaultFormatter.prototype.checkExportIdentifier = function (node) {
if (t.isIdentifier(node, { name: "__esModule" })) {
throw this.file.errorWithNode(node, messages.get("modulesIllegalExportName", node.name));
}
};
DefaultFormatter.prototype.exportSpecifier = function (specifier, node, nodes) {
if (node.source) {
var ref = this.getExternalReference(node, nodes);
if (t.isExportBatchSpecifier(specifier)) {
// export * from "foo";
nodes.push(this.buildExportsWildcard(ref, node));
} else {
if (t.isSpecifierDefault(specifier) && !this.noInteropRequireExport) {
// importing a default so we need to normalize it
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
} else {
ref = t.memberExpression(ref, t.getSpecifierId(specifier));
}
// export { foo } from "test";
nodes.push(this.buildExportsAssignment(
t.getSpecifierName(specifier),
ref,
node
));
}
} else {
// export { foo };
nodes.push(this.buildExportsAssignment(t.getSpecifierName(specifier), specifier.id, node));
}
};
DefaultFormatter.prototype.buildExportsWildcard = function (objectIdentifier) {
return t.expressionStatement(t.callExpression(this.file.addHelper("defaults"), [
t.identifier("exports"),
t.callExpression(this.file.addHelper("interop-require-wildcard"), [objectIdentifier])
]));
};
DefaultFormatter.prototype.buildExportsAssignment = function (id, init) {
this.checkExportIdentifier(id);
return util.template("exports-assign", {
VALUE: init,
KEY: id
}, true);
};
DefaultFormatter.prototype.exportDeclaration = function (node, nodes) {
var declar = node.declaration;
var id = declar.id;
if (node.default) {
id = t.identifier("default");
}
var assign;
if (t.isVariableDeclaration(declar)) {
for (var i = 0; i < declar.declarations.length; i++) {
var decl = declar.declarations[i];
decl.init = this.buildExportsAssignment(decl.id, decl.init, node).expression;
var newDeclar = t.variableDeclaration(declar.kind, [decl]);
if (i === 0) t.inherits(newDeclar, declar);
nodes.push(newDeclar);
}
} else {
var ref = declar;
if (t.isFunctionDeclaration(declar) || t.isClassDeclaration(declar)) {
ref = declar.id;
nodes.push(declar);
}
assign = this.buildExportsAssignment(id, ref, node);
nodes.push(assign);
this._hoistExport(declar, assign);
}
};

View File

@@ -1,108 +0,0 @@
"use strict";
module.exports = AMDFormatter;
var DefaultFormatter = require("./_default");
var CommonFormatter = require("./common");
var includes = require("lodash/collection/includes");
var values = require("lodash/object/values");
var util = require("../../util");
var t = require("../../types");
function AMDFormatter() {
CommonFormatter.apply(this, arguments);
}
util.inherits(AMDFormatter, DefaultFormatter);
AMDFormatter.prototype.init = CommonFormatter.prototype.init;
AMDFormatter.prototype.buildDependencyLiterals = function () {
var names = [];
for (var name in this.ids) {
names.push(t.literal(name));
}
return names;
};
/**
* Wrap the entire body in a `define` wrapper.
*/
AMDFormatter.prototype.transform = function (program) {
var body = program.body;
// build an array of module names
var names = [t.literal("exports")];
if (this.passModuleArg) names.push(t.literal("module"));
names = names.concat(this.buildDependencyLiterals());
names = t.arrayExpression(names);
// build up define container
var params = values(this.ids);
if (this.passModuleArg) params.unshift(t.identifier("module"));
params.unshift(t.identifier("exports"));
var container = t.functionExpression(null, params, t.blockStatement(body));
var defineArgs = [names, container];
var moduleName = this.getModuleName();
if (moduleName) defineArgs.unshift(t.literal(moduleName));
var call = t.callExpression(t.identifier("define"), defineArgs);
program.body = [t.expressionStatement(call)];
};
/**
* Get the AMD module name that we'll prepend to the wrapper
* to define this module
*/
AMDFormatter.prototype.getModuleName = function () {
if (this.file.opts.moduleIds) {
return DefaultFormatter.prototype.getModuleName.apply(this, arguments);
} else {
return null;
}
};
AMDFormatter.prototype._getExternalReference = function (node) {
return this.scope.generateUidIdentifier(node.source.value);
};
AMDFormatter.prototype.importDeclaration = function (node) {
this.getExternalReference(node);
};
AMDFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
var key = t.getSpecifierName(specifier);
var ref = this.getExternalReference(node);
if (includes(this.file.dynamicImportedNoDefault, node)) {
// Prevent unnecessary renaming of dynamic imports.
this.ids[node.source.value] = ref;
} else if (t.isImportBatchSpecifier(specifier)) {
// import * as bar from "foo";
} else if (!includes(this.file.dynamicImported, node) && t.isSpecifierDefault(specifier) && !this.noInteropRequireImport) {
// import foo from "foo";
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
} else {
// import {foo} from "foo";
ref = t.memberExpression(ref, t.getSpecifierId(specifier), false);
}
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(key, ref)
]));
};
AMDFormatter.prototype.exportDeclaration = function (node) {
if (this.doDefaultExportInterop(node)) {
this.passModuleArg = true;
}
CommonFormatter.prototype.exportDeclaration.apply(this, arguments);
};

View File

@@ -1,13 +0,0 @@
"use strict";
module.exports = CommonStandardFormatter;
var CommonStrictFormatter = require("./common-strict");
var util = require("../../util");
function CommonStandardFormatter() {
this.noInteropRequireImport = true;
CommonStrictFormatter.apply(this, arguments);
}
util.inherits(CommonStandardFormatter, CommonStrictFormatter);

View File

@@ -1,104 +0,0 @@
"use strict";
module.exports = CommonJSFormatter;
var DefaultFormatter = require("./_default");
var includes = require("lodash/collection/includes");
var util = require("../../util");
var t = require("../../types");
function CommonJSFormatter() {
DefaultFormatter.apply(this, arguments);
}
util.inherits(CommonJSFormatter, DefaultFormatter);
CommonJSFormatter.prototype.init = function () {
var file = this.file;
var scope = file.scope;
scope.rename("module");
if (!this.noInteropRequireImport && this.hasNonDefaultExports) {
file.ast.program.body.push(util.template("exports-module-declaration", true));
}
};
CommonJSFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
var variableName = t.getSpecifierName(specifier);
var ref = this.getExternalReference(node, nodes);
// import foo from "foo";
if (t.isSpecifierDefault(specifier)) {
if (!includes(this.file.dynamicImportedNoDefault, node)) {
if (this.noInteropRequireImport || includes(this.file.dynamicImported, node)) {
ref = t.memberExpression(ref, t.identifier("default"));
} else {
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
}
}
nodes.push(t.variableDeclaration("var", [t.variableDeclarator(variableName, ref)]));
} else {
if (specifier.type === "ImportBatchSpecifier") {
if (!this.noInteropRequireImport) {
ref = t.callExpression(this.file.addHelper("interop-require-wildcard"), [ref]);
}
// import * as bar from "foo";
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(variableName, ref)
]));
} else {
// import { foo } from "foo";
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(
variableName,
t.memberExpression(ref, t.getSpecifierId(specifier))
)
]));
}
}
};
CommonJSFormatter.prototype.importDeclaration = function (node, nodes) {
// import "foo";
nodes.push(util.template("require", {
MODULE_NAME: node.source
}, true));
};
CommonJSFormatter.prototype.exportDeclaration = function (node, nodes) {
if (this.doDefaultExportInterop(node)) {
var declar = node.declaration;
var assign = util.template("exports-default-assign", {
VALUE: this._pushStatement(declar, nodes)
}, true);
if (t.isFunctionDeclaration(declar)) {
// we can hoist this assignment to the top of the file
assign._blockHoist = 3;
}
nodes.push(assign);
return;
}
DefaultFormatter.prototype.exportDeclaration.apply(this, arguments);
};
CommonJSFormatter.prototype._getExternalReference = function (node, nodes) {
var source = node.source.value;
var call = t.callExpression(t.identifier("require"), [node.source]);
if (this.localImportOccurences[source] > 1) {
var uid = this.scope.generateUidIdentifier(source);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(uid, call)
]));
return uid;
} else {
return call;
}
};

View File

@@ -1,20 +0,0 @@
"use strict";
module.exports = IgnoreFormatter;
var t = require("../../types");
function IgnoreFormatter() {
}
IgnoreFormatter.prototype.exportDeclaration = function (node, nodes) {
var declar = t.toStatement(node.declaration, true);
if (declar) nodes.push(t.inherits(declar, node));
};
IgnoreFormatter.prototype.importDeclaration =
IgnoreFormatter.prototype.importSpecifier =
IgnoreFormatter.prototype.exportSpecifier = function () {
};

View File

@@ -1,11 +0,0 @@
module.exports = {
commonStandard: require("./common-standard"),
commonStrict: require("./common-strict"),
amdStrict: require("./amd-strict"),
umdStrict: require("./umd-strict"),
common: require("./common"),
system: require("./system"),
ignore: require("./ignore"),
amd: require("./amd"),
umd: require("./umd")
};

View File

@@ -1,201 +0,0 @@
"use strict";
module.exports = SystemFormatter;
var DefaultFormatter = require("./_default");
var AMDFormatter = require("./amd");
var useStrict = require("../helpers/use-strict");
var util = require("../../util");
var t = require("../../types");
var last = require("lodash/array/last");
var each = require("lodash/collection/each");
var map = require("lodash/collection/map");
function SystemFormatter(file) {
this.exportIdentifier = file.scope.generateUidIdentifier("export");
this.noInteropRequireExport = true;
this.noInteropRequireImport = true;
DefaultFormatter.apply(this, arguments);
}
util.inherits(SystemFormatter, AMDFormatter);
SystemFormatter.prototype.init = function () {};
SystemFormatter.prototype._addImportSource = function (node, exportNode) {
node._importSource = exportNode.source && exportNode.source.value;
return node;
};
SystemFormatter.prototype.buildExportsWildcard = function (objectIdentifier, node) {
var leftIdentifier = this.scope.generateUidIdentifier("key");
var valIdentifier = t.memberExpression(objectIdentifier, leftIdentifier, true);
var left = t.variableDeclaration("var", [
t.variableDeclarator(leftIdentifier)
]);
var right = objectIdentifier;
var block = t.blockStatement([
t.expressionStatement(this.buildExportCall(leftIdentifier, valIdentifier))
]);
return this._addImportSource(t.forInStatement(left, right, block), node);
};
SystemFormatter.prototype.buildExportsAssignment = function (id, init, node) {
var call = this.buildExportCall(t.literal(id.name), init, true);
return this._addImportSource(call, node);
};
SystemFormatter.prototype.remapExportAssignment = function (node) {
return this.buildExportCall(t.literal(node.left.name), node);
};
SystemFormatter.prototype.buildExportCall = function (id, init, isStatement) {
var call = t.callExpression(this.exportIdentifier, [id, init]);
if (isStatement) {
return t.expressionStatement(call);
} else {
return call;
}
};
SystemFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
AMDFormatter.prototype.importSpecifier.apply(this, arguments);
this._addImportSource(last(nodes), node);
};
var runnerSettersVisitor = {
enter: function (node, parent, scope, state) {
if (node._importSource === state.source) {
if (t.isVariableDeclaration(node)) {
each(node.declarations, function (declar) {
state.hoistDeclarators.push(t.variableDeclarator(declar.id));
state.nodes.push(t.expressionStatement(
t.assignmentExpression("=", declar.id, declar.init)
));
});
} else {
state.nodes.push(node);
}
this.remove();
}
}
};
SystemFormatter.prototype.buildRunnerSetters = function (block, hoistDeclarators) {
var scope = this.file.scope;
return t.arrayExpression(map(this.ids, function (uid, source) {
var state = {
source: source,
nodes: [],
hoistDeclarators: hoistDeclarators
};
scope.traverse(block, runnerSettersVisitor, state);
return t.functionExpression(null, [uid], t.blockStatement(state.nodes));
}));
};
var hoistVariablesVisitor = {
enter: function (node, parent, scope, hoistDeclarators) {
if (t.isFunction(node)) {
// nothing inside is accessible
return this.skip();
}
if (t.isVariableDeclaration(node)) {
if (node.kind !== "var" && !t.isProgram(parent)) { // let, const
// can't be accessed
return;
}
// ignore block hoisted nodes as these can be left in
if (node._blockHoist) return;
var nodes = [];
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
hoistDeclarators.push(t.variableDeclarator(declar.id));
if (declar.init) {
// no initializer so we can just hoist it as-is
var assign = t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init));
nodes.push(assign);
}
}
// for (var i in test)
// for (var i = 0;;)
if (t.isFor(parent)) {
if (parent.left === node) {
return node.declarations[0].id;
}
if (parent.init === node) {
return t.toSequenceExpression(nodes, scope);
}
}
return nodes;
}
}
};
var hoistFunctionsVisitor = {
enter: function (node, parent, scope, handlerBody) {
if (t.isFunction(node)) this.skip();
if (t.isFunctionDeclaration(node) || node._blockHoist) {
handlerBody.push(node);
this.remove();
}
}
};
SystemFormatter.prototype.transform = function (program) {
var hoistDeclarators = [];
var moduleName = this.getModuleName();
var moduleNameLiteral = t.literal(moduleName);
var block = t.blockStatement(program.body);
var runner = util.template("system", {
MODULE_NAME: moduleNameLiteral,
MODULE_DEPENDENCIES: t.arrayExpression(this.buildDependencyLiterals()),
EXPORT_IDENTIFIER: this.exportIdentifier,
SETTERS: this.buildRunnerSetters(block, hoistDeclarators),
EXECUTE: t.functionExpression(null, [], block)
}, true);
var handlerBody = runner.expression.arguments[2].body.body;
if (!moduleName) runner.expression.arguments.shift();
var returnStatement = handlerBody.pop();
// hoist up all variable declarations
this.file.scope.traverse(block, hoistVariablesVisitor, hoistDeclarators);
if (hoistDeclarators.length) {
var hoistDeclar = t.variableDeclaration("var", hoistDeclarators);
hoistDeclar._blockHoist = true;
handlerBody.unshift(hoistDeclar);
}
// hoist up function declarations for circular references
this.file.scope.traverse(block, hoistFunctionsVisitor, handlerBody);
handlerBody.push(returnStatement);
if (useStrict.has(block)) {
handlerBody.unshift(block.body.shift());
}
program.body = [runner];
};

View File

@@ -1,73 +0,0 @@
"use strict";
module.exports = UMDFormatter;
var AMDFormatter = require("./amd");
var util = require("../../util");
var t = require("../../types");
var values = require("lodash/object/values");
function UMDFormatter() {
AMDFormatter.apply(this, arguments);
}
util.inherits(UMDFormatter, AMDFormatter);
UMDFormatter.prototype.transform = function (program) {
var body = program.body;
// build an array of module names
var names = [];
for (var name in this.ids) {
names.push(t.literal(name));
}
// factory
var ids = values(this.ids);
var args = [t.identifier("exports")];
if (this.passModuleArg) args.push(t.identifier("module"));
args = args.concat(ids);
var factory = t.functionExpression(null, args, t.blockStatement(body));
// amd
var defineArgs = [t.literal("exports")];
if (this.passModuleArg) defineArgs.push(t.literal("module"));
defineArgs = defineArgs.concat(names);
defineArgs = [t.arrayExpression(defineArgs)];
// common
var testExports = util.template("test-exports");
var testModule = util.template("test-module");
var commonTests = this.passModuleArg ? t.logicalExpression("&&", testExports, testModule) : testExports;
var commonArgs = [t.identifier("exports")];
if (this.passModuleArg) commonArgs.push(t.identifier("module"));
commonArgs = commonArgs.concat(names.map(function (name) {
return t.callExpression(t.identifier("require"), [name]);
}));
// globals
//var umdArgs = [];
//
var moduleName = this.getModuleName();
if (moduleName) defineArgs.unshift(t.literal(moduleName));
var runner = util.template("umd-runner-body", {
AMD_ARGUMENTS: defineArgs,
COMMON_TEST: commonTests,
COMMON_ARGUMENTS: commonArgs
});
//
var call = t.callExpression(runner, [factory]);
program.body = [t.expressionStatement(call)];
};

View File

@@ -1,3 +0,0 @@
{
"blacklist": ["useStrict"]
}

View File

@@ -1,3 +0,0 @@
for (var ITERATOR_KEY = OBJECT[Symbol.iterator](), STEP_KEY; !(STEP_KEY = ITERATOR_KEY.next()).done; ) {
}

View File

@@ -1,4 +0,0 @@
(function (child, staticProps, instanceProps) {
if (staticProps) Object.defineProperties(child, staticProps);
if (instanceProps) Object.defineProperties(child.prototype, instanceProps);
})

View File

@@ -1,2 +0,0 @@
var helpers = exports.default = {};
exports.__esModule = true;

View File

@@ -1,3 +0,0 @@
{
FUNCTION_ID:while (true) BLOCK
}

View File

@@ -1,23 +0,0 @@
(function () {
function Tail(func, args, context) {
this.func = func;
this.args = args;
this.context = context;
}
Tail.prototype._isTailDescriptor = true;
var isRunning = false;
return function (func, args, context) {
var result = new Tail(func, args, context);
if (!isRunning) {
isRunning = true;
do {
result = result.func.apply(result.context, result.args);
} while (result instanceof Tail || (result && result._isTailDescriptor));
isRunning = false;
}
return result;
};
})()

View File

@@ -1,63 +0,0 @@
module.exports = TransformerPass;
var includes = require("lodash/collection/includes");
/**
* This class is responsible for traversing over the provided `File`s
* AST and running it's parent transformers handlers over it.
*/
function TransformerPass(file, transformer) {
this.transformer = transformer;
this.shouldRun = !transformer.check;
this.handlers = transformer.handlers;
this.file = file;
}
TransformerPass.prototype.canRun = function () {
var transformer = this.transformer;
var opts = this.file.opts;
var key = transformer.key;
// internal
if (key[0] === "_") return true;
// blacklist
var blacklist = opts.blacklist;
if (blacklist.length && includes(blacklist, key)) return false;
// whitelist
var whitelist = opts.whitelist;
if (whitelist.length) return includes(whitelist, key);
// optional
if (transformer.optional && !includes(opts.optional, key)) return false;
// experimental
if (transformer.experimental && !opts.experimental) return false;
// playground
if (transformer.playground && !opts.playground) return false;
return true;
};
TransformerPass.prototype.checkNode = function (node) {
var check = this.transformer.check;
if (check) {
return this.shouldRun = check(node);
} else {
return true;
}
};
TransformerPass.prototype.transform = function () {
if (!this.shouldRun) return;
var file = this.file;
file.debug("Running transformer " + this.transformer.key);
file.scope.traverse(file.ast, this.handlers, file);
};

View File

@@ -1,75 +0,0 @@
"use strict";
module.exports = Transformer;
var TransformerPass = require("./transformer-pass");
var isFunction = require("lodash/lang/isFunction");
var traverse = require("../traversal");
var isObject = require("lodash/lang/isObject");
var clone = require("../helpers/clone");
var each = require("lodash/collection/each");
/**
* This is the class responsible for normalising a transformers handlers
* as well as constructing a `TransformerPass` that is repsonsible for
* actually running the transformer over the provided `File`.
*/
function Transformer(key, transformer, opts) {
transformer = clone(transformer);
var take = function (key) {
var val = transformer[key];
delete transformer[key];
return val;
};
this.manipulateOptions = take("manipulateOptions");
this.check = take("check");
this.post = take("post");
this.pre = take("pre");
this.experimental = !!take("experimental");
this.playground = !!take("playground");
this.secondPass = !!take("secondPass");
this.optional = !!take("optional");
this.handlers = this.normalize(transformer);
this.opts = opts || {};
this.key = key;
}
Transformer.prototype.normalize = function (transformer) {
var self = this;
if (isFunction(transformer)) {
transformer = { ast: transformer };
}
traverse.explode(transformer);
each(transformer, function (fns, type) {
// hidden property
if (type[0] === "_") {
self[type] = fns;
return;
}
if (type === "enter" || type === "exit") return;
if (isFunction(fns)) fns = { enter: fns };
if (!isObject(fns)) return;
if (!fns.enter) fns.enter = function () { };
if (!fns.exit) fns.exit = function () { };
transformer[type] = fns;
});
return transformer;
};
Transformer.prototype.buildPass = function (file) {
return new TransformerPass(file, this);
};

View File

@@ -1,41 +0,0 @@
{
"specNoForInOfAssignment": "validation.noForInOfAssignment",
"specSetters": "validation.setters",
"specBlockScopedFunctions": "spec.blockScopedFunctions",
"malletOperator": "playground.malletOperator",
"methodBinding": "playground.methodBinding",
"memoizationOperator": "playground.memoizationOperator",
"objectGetterMemoization": "playground.objectGetterMemoization",
"modules": "es6.modules",
"propertyNameShorthand": "es6.properties.shorthand",
"arrayComprehension": "es7.comprehensions",
"generatorComprehension": "es7.comprehensions",
"arrowFunctions": "es6.arrowFunctions",
"classes": "es6.classes",
"objectSpread": "es7.objectRestSpread",
"es7.objectSpread": "es7.objectRestSpread",
"exponentiationOperator": "es7.exponentiationOperator",
"spread": "es6.spread",
"templateLiterals": "es6.templateLiterals",
"propertyMethodAssignment": "es6.properties.shorthand",
"computedPropertyNames": "es6.properties.computed",
"defaultParameters": "es6.parameters.default",
"restParameters": "es6.parameters.rest",
"destructuring": "es6.destructuring",
"forOf": "es6.forOf",
"unicodeRegex": "es6.unicodeRegex",
"abstractReferences": "es7.abstractReferences",
"constants": "es6.constants",
"letScoping": "es6.letScoping",
"blockScopingTDZ": "es6.blockScopingTDZ",
"generators": "regenerator",
"protoToAssign": "spec.protoToAssign",
"typeofSymbol": "spec.typeofSymbol",
"coreAliasing": "selfContained",
"undefinedToVoid": "spec.undefinedToVoid",
"undeclaredVariableCheck": "validation.undeclaredVariableCheck",
"specPropertyLiterals": "es3.propertyLiterals",
"specMemberExpressionLiterals": "es3.memberExpressionLiterals",
"minification.propertyLiterals": "es3.propertyLiterals",
"minification.memberExpressionLiterals": "es3.memberExpressionLiterals"
}

View File

@@ -1,15 +0,0 @@
"use strict";
var t = require("../../../types");
exports.check = t.isArrowFunctionExpression;
exports.ArrowFunctionExpression = function (node) {
t.ensureBlock(node);
node._aliasFunction = "arrow";
node.expression = false;
node.type = "FunctionExpression";
return node;
};

View File

@@ -1,540 +0,0 @@
"use strict";
var traverse = require("../../../traversal");
var object = require("../../../helpers/object");
var util = require("../../../util");
var t = require("../../../types");
var values = require("lodash/object/values");
var extend = require("lodash/object/extend");
exports.check = function (node) {
return t.isVariableDeclaration(node) && (node.kind === "let" || node.kind === "const");
};
var isLet = function (node, parent) {
if (!t.isVariableDeclaration(node)) return false;
if (node._let) return true;
if (node.kind !== "let") return false;
// https://github.com/6to5/6to5/issues/255
if (isLetInitable(node, parent)) {
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
declar.init = declar.init || t.identifier("undefined");
}
}
node._let = true;
node.kind = "var";
return true;
};
var isLetInitable = function (node, parent) {
return !t.isFor(parent) || t.isFor(parent) && parent.left !== node;
};
var isVar = function (node, parent) {
return t.isVariableDeclaration(node, { kind: "var" }) && !isLet(node, parent);
};
var standardizeLets = function (declars) {
for (var i = 0; i < declars.length; i++) {
delete declars[i]._let;
}
};
exports.VariableDeclaration = function (node, parent, scope, file) {
if (!isLet(node, parent)) return;
if (isLetInitable(node) && file.transformers["es6.blockScopingTDZ"].canRun()) {
var nodes = [node];
for (var i = 0; i < node.declarations.length; i++) {
var decl = node.declarations[i];
if (decl.init) {
var assign = t.assignmentExpression("=", decl.id, decl.init);
assign._ignoreBlockScopingTDZ = true;
nodes.push(t.expressionStatement(assign));
}
decl.init = file.addHelper("temporal-undefined");
}
node._blockHoist = 2;
return nodes;
}
};
exports.Loop = function (node, parent, scope, file) {
var init = node.left || node.init;
if (isLet(init, node)) {
t.ensureBlock(node);
node.body._letDeclarators = [init];
}
var blockScoping = new BlockScoping(node, node.body, parent, scope, file);
blockScoping.run();
};
exports.Program =
exports.BlockStatement = function (block, parent, scope, file) {
if (!t.isLoop(parent)) {
var blockScoping = new BlockScoping(false, block, parent, scope, file);
blockScoping.run();
}
};
/**
* Description
*
* @param {Boolean|Node} loopParent
* @param {Node} block
* @param {Node} parent
* @param {Scope} scope
* @param {File} file
*/
function BlockScoping(loopParent, block, parent, scope, file) {
this.loopParent = loopParent;
this.parent = parent;
this.scope = scope;
this.block = block;
this.file = file;
this.outsideLetReferences = object();
this.hasLetReferences = false;
this.letReferences = block._letReferences = object();
this.body = [];
}
/**
* Start the ball rolling.
*/
BlockScoping.prototype.run = function () {
var block = this.block;
if (block._letDone) return;
block._letDone = true;
var needsClosure = this.getLetReferences();
// this is a block within a `Function/Program` so we can safely leave it be
if (t.isFunction(this.parent) || t.isProgram(this.block)) return;
// we can skip everything
if (!this.hasLetReferences) return;
if (needsClosure) {
this.needsClosure();
} else {
this.remap();
}
};
function replace(node, parent, scope, remaps) {
if (!t.isReferencedIdentifier(node, parent)) return;
var remap = remaps[node.name];
if (!remap) return;
var ownBinding = scope.getBindingIdentifier(node.name);
if (ownBinding === remap.binding) {
node.name = remap.uid;
} else {
// scope already has it's own binding that doesn't
// match the one we have a stored replacement for
if (this) this.skip();
}
}
var replaceVisitor = {
enter: replace
};
function traverseReplace(node, parent, scope, remaps) {
replace(node, parent, scope, remaps);
scope.traverse(node, replaceVisitor, remaps);
}
/**
* Description
*/
BlockScoping.prototype.remap = function () {
var hasRemaps = false;
var letRefs = this.letReferences;
var scope = this.scope;
// alright, so since we aren't wrapping this block in a closure
// we have to check if any of our let variables collide with
// those in upper scopes and then if they do, generate a uid
// for them and replace all references with it
var remaps = object();
for (var key in letRefs) {
// just an Identifier node we collected in `getLetReferences`
// this is the defining identifier of a declaration
var ref = letRefs[key];
if (scope.parentHasBinding(key) || scope.hasGlobal(key)) {
var uid = scope.generateUidIdentifier(ref.name).name;
ref.name = uid;
hasRemaps = true;
remaps[key] = remaps[uid] = {
binding: ref,
uid: uid
};
}
}
if (!hasRemaps) return;
//
var loopParent = this.loopParent;
if (loopParent) {
traverseReplace(loopParent.right, loopParent, scope, remaps);
traverseReplace(loopParent.test, loopParent, scope, remaps);
traverseReplace(loopParent.update, loopParent, scope, remaps);
}
scope.traverse(this.block, replaceVisitor, remaps);
};
/**
* Description
*/
BlockScoping.prototype.needsClosure = function () {
var block = this.block;
// if we're inside of a for loop then we search to see if there are any
// `break`s, `continue`s, `return`s etc
this.has = this.checkLoop();
// hoist var references to retain scope
this.hoistVarDeclarations();
// turn outsideLetReferences into an array
var params = values(this.outsideLetReferences);
// build the closure that we're going to wrap the block with
var fn = t.functionExpression(null, params, t.blockStatement(block.body));
fn._aliasFunction = true;
// replace the current block body with the one we're going to build
block.body = this.body;
// build a call and a unique id that we can assign the return value to
var call = t.callExpression(fn, params);
var ret = this.scope.generateUidIdentifier("ret");
// handle generators
var hasYield = traverse.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES);
if (hasYield) {
fn.generator = true;
call = t.yieldExpression(call, true);
}
// handlers async functions
var hasAsync = traverse.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES);
if (hasAsync) {
fn.async = true;
call = t.awaitExpression(call, true);
}
this.build(ret, call);
};
var letReferenceFunctionVisitor = {
enter: function (node, parent, scope, state) {
// not a direct reference
if (!t.isReferencedIdentifier(node, parent)) return;
// this scope has a variable with the same name so it couldn't belong
// to our let scope
if (scope.hasOwnBinding(node.name)) return;
// not a part of our scope
if (!state.letReferences[node.name]) return;
state.closurify = true;
}
};
var letReferenceBlockVisitor = {
enter: function (node, parent, scope, state) {
if (t.isFunction(node)) {
scope.traverse(node, letReferenceFunctionVisitor, state);
return this.skip();
}
}
};
/**
* Description
*/
BlockScoping.prototype.getLetReferences = function () {
var block = this.block;
var declarators = block._letDeclarators || [];
var declar;
//
for (var i = 0; i < declarators.length; i++) {
declar = declarators[i];
extend(this.outsideLetReferences, t.getBindingIdentifiers(declar));
}
//
if (block.body) {
for (i = 0; i < block.body.length; i++) {
declar = block.body[i];
if (isLet(declar, block)) {
declarators = declarators.concat(declar.declarations);
}
}
}
//
for (i = 0; i < declarators.length; i++) {
declar = declarators[i];
var keys = t.getBindingIdentifiers(declar);
extend(this.letReferences, keys);
this.hasLetReferences = true;
}
// no let references so we can just quit
if (!this.hasLetReferences) return;
// set let references to plain var references
standardizeLets(declarators);
var state = {
letReferences: this.letReferences,
closurify: false
};
// traverse through this block, stopping on functions and checking if they
// contain any local let references
this.scope.traverse(this.block, letReferenceBlockVisitor, state);
return state.closurify;
};
var loopNodeTo = function (node) {
if (t.isBreakStatement(node)) {
return "break";
} else if (t.isContinueStatement(node)) {
return "continue";
}
};
var loopVisitor = {
enter: function (node, parent, scope, state) {
var replace;
if (t.isLoop(node)) {
state.ignoreLabeless = true;
scope.traverse(node, loopVisitor, state);
state.ignoreLabeless = false;
}
if (t.isFunction(node) || t.isLoop(node)) {
return this.skip();
}
var loopText = loopNodeTo(node);
if (loopText) {
if (node.label) {
// we shouldn't be transforming this because it exists somewhere inside
if (state.innerLabels.indexOf(node.label.name) >= 0) {
return;
}
loopText = loopText + "|" + node.label.name;
} else {
// we shouldn't be transforming these statements because
// they don't refer to the actual loop we're scopifying
if (state.ignoreLabeless) return;
// break statements mean something different in this context
if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return;
}
state.hasBreakContinue = true;
state.map[loopText] = node;
replace = t.literal(loopText);
}
if (t.isReturnStatement(node)) {
state.hasReturn = true;
replace = t.objectExpression([
t.property("init", t.identifier("v"), node.argument || t.identifier("undefined"))
]);
}
if (replace) {
replace = t.returnStatement(replace);
return t.inherits(replace, node);
}
}
};
var loopLabelVisitor = {
enter: function (node, parent, scope, state) {
if (t.isLabeledStatement(node)) {
state.innerLabels.push(node.label.name);
}
}
};
/**
* If we're inside of a loop then traverse it and check if it has one of
* the following node types `ReturnStatement`, `BreakStatement`,
* `ContinueStatement` and replace it with a return value that we can track
* later on.
*
* @returns {Object}
*/
BlockScoping.prototype.checkLoop = function () {
var state = {
hasBreakContinue: false,
ignoreLabeless: false,
innerLabels: [],
hasReturn: false,
isLoop: !!this.loopParent,
map: {}
};
this.scope.traverse(this.block, loopLabelVisitor, state);
this.scope.traverse(this.block, loopVisitor, state);
return state;
};
var hoistVarDeclarationsVisitor = {
enter: function (node, parent, scope, self) {
if (t.isForStatement(node)) {
if (isVar(node.init, node)) {
node.init = t.sequenceExpression(self.pushDeclar(node.init));
}
} else if (t.isFor(node)) {
if (isVar(node.left, node)) {
node.left = node.left.declarations[0].id;
}
} else if (isVar(node, parent)) {
return self.pushDeclar(node).map(t.expressionStatement);
} else if (t.isFunction(node)) {
return this.skip();
}
}
};
/**
* Hoist all var declarations in this block to before it so they retain scope
* once we wrap everything in a closure.
*/
BlockScoping.prototype.hoistVarDeclarations = function () {
traverse(this.block, hoistVarDeclarationsVisitor, this.scope, this);
};
/**
* Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with
* their declarations hoisted to before the closure wrapper.
*
* @param {Node} node VariableDeclaration
* @returns {Array}
*/
BlockScoping.prototype.pushDeclar = function (node) {
this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
return t.variableDeclarator(declar.id);
})));
var replace = [];
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
if (!declar.init) continue;
var expr = t.assignmentExpression("=", declar.id, declar.init);
replace.push(t.inherits(expr, declar));
}
return replace;
};
/**
* Push the closure to the body.
*
* @param {Node} ret Identifier
* @param {Node} call CallExpression
*/
BlockScoping.prototype.build = function (ret, call) {
var has = this.has;
if (has.hasReturn || has.hasBreakContinue) {
this.buildHas(ret, call);
} else {
this.body.push(t.expressionStatement(call));
}
};
/**
* Description
*
* @param {Node} ret Identifier
* @param {Node} call CallExpression
*/
BlockScoping.prototype.buildHas = function (ret, call) {
var body = this.body;
body.push(t.variableDeclaration("var", [
t.variableDeclarator(ret, call)
]));
var loopParent = this.loopParent;
var retCheck;
var has = this.has;
var cases = [];
if (has.hasReturn) {
// typeof ret === "object"
retCheck = util.template("let-scoping-return", {
RETURN: ret
});
}
if (has.hasBreakContinue) {
if (!loopParent) {
throw new Error("Has no loop parent but we're trying to reassign breaks " +
"and continues, something is going wrong here.");
}
for (var key in has.map) {
cases.push(t.switchCase(t.literal(key), [has.map[key]]));
}
if (has.hasReturn) {
cases.push(t.switchCase(null, [retCheck]));
}
if (cases.length === 1) {
var single = cases[0];
body.push(t.ifStatement(
t.binaryExpression("===", ret, single.test),
single.consequent[0]
));
} else {
body.push(t.switchStatement(ret, cases));
}
} else {
if (has.hasReturn) body.push(retCheck);
}
};

View File

@@ -1,296 +0,0 @@
"use strict";
var ReplaceSupers = require("../../helpers/replace-supers");
var nameMethod = require("../../helpers/name-method");
var defineMap = require("../../helpers/define-map");
var messages = require("../../../messages");
var util = require("../../../util");
var t = require("../../../types");
exports.check = t.isClass;
exports.ClassDeclaration = function (node, parent, scope, file) {
return new ClassTransformer(node, file, scope, true).run();
};
exports.ClassExpression = function (node, parent, scope, file) {
if (!node.id) {
if (t.isProperty(parent) && parent.value === node && !parent.computed && t.isIdentifier(parent.key)) {
// var o = { foo: class {} };
node.id = parent.key;
}
if (t.isVariableDeclarator(parent) && t.isIdentifier(parent.id)) {
// var foo = class {};
node.id = parent.id;
}
}
return new ClassTransformer(node, file, scope, false).run();
};
/**
* Description
*
* @param {Node} node
* @param {File} file
* @param {Scope} scope
* @param {Boolean} isStatement
*/
function ClassTransformer(node, file, scope, isStatement) {
this.isStatement = isStatement;
this.scope = scope;
this.node = node;
this.file = file;
this.hasInstanceMutators = false;
this.hasStaticMutators = false;
this.instanceMutatorMap = {};
this.staticMutatorMap = {};
this.hasConstructor = false;
this.className = node.id || scope.generateUidIdentifier("class");
this.superName = node.superClass || t.identifier("Function");
this.hasSuper = !!node.superClass;
this.isLoose = file.isLoose("es6.classes");
}
/**
* Description
*
* @returns {Array}
*/
ClassTransformer.prototype.run = function () {
var superName = this.superName;
var className = this.className;
var file = this.file;
//
var body = this.body = [];
var constructorBody = t.blockStatement([
t.expressionStatement(t.callExpression(file.addHelper("class-call-check"), [
t.thisExpression(),
className
]))
]);
var constructor;
if (this.node.id) {
constructor = t.functionDeclaration(className, [], constructorBody);
body.push(constructor);
} else {
constructor = t.functionExpression(null, [], constructorBody);
body.push(t.variableDeclaration("var", [
t.variableDeclarator(className, constructor)
]));
}
this.constructor = constructor;
var closureParams = [];
var closureArgs = [];
//
if (this.hasSuper) {
closureArgs.push(superName);
if (!t.isIdentifier(superName)) {
superName = this.scope.generateUidBasedOnNode(superName, this.file);
}
closureParams.push(superName);
this.superName = superName;
body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"), [className, superName])));
}
this.buildBody();
t.inheritsComments(body[0], this.node);
var init;
if (body.length === 1) {
// only a constructor so no need for a closure container
init = t.toExpression(constructor);
} else {
body.push(t.returnStatement(className));
init = t.callExpression(
t.functionExpression(null, closureParams, t.blockStatement(body)),
closureArgs
);
}
if (this.isStatement) {
return t.variableDeclaration("let", [
t.variableDeclarator(className, init)
]);
} else {
return init;
}
};
/**
* Description
*/
ClassTransformer.prototype.buildBody = function () {
var constructor = this.constructor;
var className = this.className;
var superName = this.superName;
var classBody = this.node.body.body;
var body = this.body;
for (var i = 0; i < classBody.length; i++) {
var node = classBody[i];
if (t.isMethodDefinition(node)) {
var replaceSupers = new ReplaceSupers({
methodNode: node,
className: this.className,
superName: this.superName,
isStatic: node.static,
isLoose: this.isLoose,
scope: this.scope,
file: this.file
}, true);
replaceSupers.replace();
if (node.key.name === "constructor") {
this.pushConstructor(node);
} else {
this.pushMethod(node);
}
} else if (t.isPrivateDeclaration(node)) {
this.closure = true;
body.unshift(node);
} else if (t.isClassProperty(node)) {
this.pushProperty(node);
}
}
// we have no constructor, we have a super, and the super doesn't appear to be falsy
if (!this.hasConstructor && this.hasSuper && !t.isFalsyExpression(superName)) {
var helperName = "class-super-constructor-call";
if (this.isLoose) helperName += "-loose";
constructor.body.body.push(util.template(helperName, {
CLASS_NAME: className,
SUPER_NAME: this.superName
}, true));
}
var instanceProps;
var staticProps;
if (this.hasInstanceMutators) {
instanceProps = defineMap.build(this.instanceMutatorMap);
}
if (this.hasStaticMutators) {
staticProps = defineMap.build(this.staticMutatorMap);
}
if (instanceProps || staticProps) {
staticProps = staticProps || t.literal(null);
var args = [className, staticProps];
if (instanceProps) args.push(instanceProps);
body.push(t.expressionStatement(
t.callExpression(this.file.addHelper("prototype-properties"), args)
));
}
};
/**
* Push a method to its respective mutatorMap.
*
* @param {Node} node MethodDefinition
*/
ClassTransformer.prototype.pushMethod = function (node) {
var methodName = node.key;
var kind = node.kind;
if (kind === "") {
nameMethod.property(node, this.file, this.scope);
if (this.isLoose) {
// use assignments instead of define properties for loose classes
var className = this.className;
if (!node.static) className = t.memberExpression(className, t.identifier("prototype"));
methodName = t.memberExpression(className, methodName, node.computed);
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value));
t.inheritsComments(expr, node);
this.body.push(expr);
return;
}
kind = "value";
}
var mutatorMap = this.instanceMutatorMap;
if (node.static) {
this.hasStaticMutators = true;
mutatorMap = this.staticMutatorMap;
} else {
this.hasInstanceMutators = true;
}
defineMap.push(mutatorMap, methodName, kind, node.computed, node);
defineMap.push(mutatorMap, methodName, "enumerable", node.computed, false);
};
/**
* Description
*
* @param {Node} node
*/
ClassTransformer.prototype.pushProperty = function (node) {
if (!node.value) return;
var key;
if (node.static) {
key = t.memberExpression(this.className, node.key);
this.body.push(
t.expressionStatement(t.assignmentExpression("=", key, node.value))
);
} else {
key = t.memberExpression(t.thisExpression(), node.key);
this.constructor.body.body.unshift(
t.expressionStatement(t.assignmentExpression("=", key, node.value))
);
}
};
/**
* Replace the constructor body of our class.
*
* @param {Node} method MethodDefinition
*/
ClassTransformer.prototype.pushConstructor = function (method) {
if (method.kind) {
throw this.file.errorWithNode(method, messages.get("classesIllegalConstructorKind"));
}
var construct = this.constructor;
var fn = method.value;
this.hasConstructor = true;
t.inherits(construct, fn);
t.inheritsComments(construct, method);
construct._ignoreUserWhitespace = true;
construct.params = fn.params;
construct.body.body = construct.body.body.concat(fn.body.body);
};

View File

@@ -1,403 +0,0 @@
"use strict";
var messages = require("../../../messages");
var t = require("../../../types");
exports.check = t.isPattern;
function DestructuringTransformer(opts) {
this.blockHoist = opts.blockHoist;
this.operator = opts.operator;
this.nodes = opts.nodes;
this.scope = opts.scope;
this.file = opts.file;
this.kind = opts.kind;
}
DestructuringTransformer.prototype.buildVariableAssignment = function (id, init) {
var op = this.operator;
if (t.isMemberExpression(id)) op = "=";
var node;
if (op) {
node = t.expressionStatement(t.assignmentExpression(op, id, init));
} else {
node = t.variableDeclaration(this.kind, [
t.variableDeclarator(id, init)
]);
}
node._blockHoist = this.blockHoist;
return node;
};
DestructuringTransformer.prototype.buildVariableDeclaration = function (id, init) {
var declar = t.variableDeclaration("var", [
t.variableDeclarator(id, init)
]);
declar._blockHoist = this.blockHoist;
return declar;
};
DestructuringTransformer.prototype.push = function (elem, parentId) {
if (t.isObjectPattern(elem)) {
this.pushObjectPattern(elem, parentId);
} else if (t.isArrayPattern(elem)) {
this.pushArrayPattern(elem, parentId);
} else if (t.isAssignmentPattern(elem)) {
this.pushAssignmentPattern(elem, parentId);
} else {
this.nodes.push(this.buildVariableAssignment(elem, parentId));
}
};
DestructuringTransformer.prototype.pushAssignmentPattern = function (pattern, parentId) {
var tempParentId = this.scope.generateUidBasedOnNode(parentId);
var declar = t.variableDeclaration("var", [
t.variableDeclarator(tempParentId, parentId)
]);
declar._blockHoist = this.blockHoist;
this.nodes.push(declar);
this.nodes.push(this.buildVariableAssignment(
pattern.left,
t.conditionalExpression(
t.binaryExpression("===", tempParentId, t.identifier("undefined")),
pattern.right,
tempParentId
)
));
};
DestructuringTransformer.prototype.pushObjectSpread = function (pattern, parentId, prop, i) {
// get all the keys that appear in this object before the current spread
var keys = [];
for (var i2 = 0; i2 < pattern.properties.length; i2++) {
var prop2 = pattern.properties[i2];
if (i2 >= i) break;
if (t.isSpreadProperty(prop2)) continue;
var key = prop2.key;
if (t.isIdentifier(key)) {
key = t.literal(prop2.key.name);
}
keys.push(key);
}
keys = t.arrayExpression(keys);
var value = t.callExpression(this.file.addHelper("object-without-properties"), [parentId, keys]);
this.nodes.push(this.buildVariableAssignment(prop.argument, value));
};
DestructuringTransformer.prototype.pushObjectProperty = function (prop, parentId) {
if (t.isLiteral(prop.key)) prop.computed = true;
var pattern2 = prop.value;
var patternId2 = t.memberExpression(parentId, prop.key, prop.computed);
if (t.isPattern(pattern2)) {
this.push(pattern2, patternId2);
} else {
this.nodes.push(this.buildVariableAssignment(pattern2, patternId2));
}
};
DestructuringTransformer.prototype.pushObjectPattern = function (pattern, parentId) {
if (!pattern.properties.length) {
this.nodes.push(t.expressionStatement(
t.callExpression(this.file.addHelper("object-destructuring-empty"), [parentId])
));
}
if (pattern.properties.length > 1 && t.isMemberExpression(parentId)) {
var temp = this.scope.generateUidBasedOnNode(parentId, this.file);
this.nodes.push(this.buildVariableDeclaration(temp, parentId));
parentId = temp;
}
for (var i = 0; i < pattern.properties.length; i++) {
var prop = pattern.properties[i];
if (t.isSpreadProperty(prop)) {
this.pushObjectSpread(pattern, parentId, prop, i);
} else {
this.pushObjectProperty(prop, parentId);
}
}
};
var hasRest = function (pattern) {
for (var i = 0; i < pattern.elements.length; i++) {
if (t.isRestElement(pattern.elements[i])) {
return true;
}
}
return false;
};
DestructuringTransformer.prototype.pushArrayPattern = function (pattern, parentId) {
if (!pattern.elements) return;
// if we have a rest then we need all the elements
var count = !hasRest(pattern) && pattern.elements.length;
var toArray = this.scope.toArray(parentId, count);
var _parentId = this.scope.generateUidBasedOnNode(parentId);
this.nodes.push(this.buildVariableDeclaration(_parentId, toArray));
parentId = _parentId;
this.scope.assignTypeGeneric(parentId.name, "Array");
for (var i = 0; i < pattern.elements.length; i++) {
var elem = pattern.elements[i];
// hole
if (!elem) continue;
var newPatternId;
if (t.isRestElement(elem)) {
newPatternId = this.scope.toArray(parentId);
if (i > 0) {
newPatternId = t.callExpression(t.memberExpression(newPatternId, t.identifier("slice")), [t.literal(i)]);
}
elem = elem.argument;
} else {
newPatternId = t.memberExpression(parentId, t.literal(i), true);
}
this.push(elem, newPatternId);
}
};
DestructuringTransformer.prototype.init = function (pattern, parentId) {
if (!t.isArrayExpression(parentId) && !t.isMemberExpression(parentId) && !t.isIdentifier(parentId)) {
var key = this.scope.generateUidBasedOnNode(parentId);
this.nodes.push(this.buildVariableDeclaration(key, parentId));
parentId = key;
}
this.push(pattern, parentId);
};
exports.ForInStatement =
exports.ForOfStatement = function (node, parent, scope, file) {
var left = node.left;
if (t.isPattern(left)) {
// for ({ length: k } in { abc: 3 });
var temp = scope.generateUidIdentifier("ref");
node.left = t.variableDeclaration("var", [
t.variableDeclarator(temp)
]);
t.ensureBlock(node);
node.body.body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(left, temp)
]));
return;
}
if (!t.isVariableDeclaration(left)) return;
var pattern = left.declarations[0].id;
if (!t.isPattern(pattern)) return;
var key = scope.generateUidIdentifier("ref");
node.left = t.variableDeclaration(left.kind, [
t.variableDeclarator(key, null)
]);
var nodes = [];
var destructuring = new DestructuringTransformer({
kind: left.kind,
file: file,
scope: scope,
nodes: nodes
});
destructuring.init(pattern, key);
t.ensureBlock(node);
var block = node.body;
block.body = nodes.concat(block.body);
};
exports.Function = function (node, parent, scope, file) {
var nodes = [];
var hasDestructuringTransformer = false;
node.params = node.params.map(function (pattern, i) {
if (!t.isPattern(pattern)) return pattern;
hasDestructuringTransformer = true;
var parentId = scope.generateUidIdentifier("ref");
var destructuring = new DestructuringTransformer({
blockHoist: node.params.length - i,
nodes: nodes,
scope: scope,
file: file,
kind: "var",
});
destructuring.init(pattern, parentId);
return parentId;
});
if (!hasDestructuringTransformer) return;
t.ensureBlock(node);
var block = node.body;
block.body = nodes.concat(block.body);
};
exports.CatchClause = function (node, parent, scope, file) {
var pattern = node.param;
if (!t.isPattern(pattern)) return;
var ref = scope.generateUidIdentifier("ref");
node.param = ref;
var nodes = [];
var destructuring = new DestructuringTransformer({
kind: "let",
file: file,
scope: scope,
nodes: nodes
});
destructuring.init(pattern, ref);
node.body.body = nodes.concat(node.body.body);
return node;
};
exports.ExpressionStatement = function (node, parent, scope, file) {
var expr = node.expression;
if (expr.type !== "AssignmentExpression") return;
if (!t.isPattern(expr.left)) return;
if (file.isConsequenceExpressionStatement(node)) return;
var nodes = [];
var ref = scope.generateUidIdentifier("ref");
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(ref, expr.right)
]));
var destructuring = new DestructuringTransformer({
operator: expr.operator,
file: file,
scope: scope,
nodes: nodes
});
destructuring.init(expr.left, ref);
return nodes;
};
exports.AssignmentExpression = function (node, parent, scope, file) {
if (!t.isPattern(node.left)) return;
var ref = scope.generateUidIdentifier("temp");
scope.push({
key: ref.name,
id: ref
});
var nodes = [];
nodes.push(t.assignmentExpression("=", ref, node.right));
var destructuring = new DestructuringTransformer({
operator: node.operator,
file: file,
scope: scope,
nodes: nodes
});
destructuring.init(node.left, ref);
nodes.push(ref);
return t.toSequenceExpression(nodes, scope);
};
var variableDeclarationhasPattern = function (node) {
for (var i = 0; i < node.declarations.length; i++) {
if (t.isPattern(node.declarations[i].id)) {
return true;
}
}
return false;
};
exports.VariableDeclaration = function (node, parent, scope, file) {
if (t.isForInStatement(parent) || t.isForOfStatement(parent)) return;
if (!variableDeclarationhasPattern(node)) return;
var nodes = [];
var declar;
for (var i = 0; i < node.declarations.length; i++) {
declar = node.declarations[i];
var patternId = declar.init;
var pattern = declar.id;
var destructuring = new DestructuringTransformer({
nodes: nodes,
scope: scope,
kind: node.kind,
file: file
});
if (t.isPattern(pattern) && patternId) {
destructuring.init(pattern, patternId);
if (+i !== node.declarations.length - 1) {
// we aren't the last declarator so let's just make the
// last transformed node inherit from us
t.inherits(nodes[nodes.length - 1], declar);
}
} else {
nodes.push(t.inherits(destructuring.buildVariableAssignment(declar.id, declar.init), declar));
}
}
if (!t.isProgram(parent) && !t.isBlockStatement(parent)) {
// https://github.com/6to5/6to5/issues/113
// for (let [x] = [0]; false;) {}
declar = null;
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
declar = declar || t.variableDeclaration(node.kind, []);
if (!t.isVariableDeclaration(node) && declar.kind !== node.kind) {
throw file.errorWithNode(node, messages.get("invalidParentForThisNode"));
}
declar.declarations = declar.declarations.concat(node.declarations);
}
return declar;
}
return nodes;
};

View File

@@ -1,34 +0,0 @@
"use strict";
var ReplaceSupers = require("../../helpers/replace-supers");
var t = require("../../../types");
exports.check = function (node) {
return t.isIdentifier(node, { name: "super" });
};
exports.Property = function (node, parent, scope, file) {
if (!node.method) return;
var value = node.value;
var thisExpr = scope.generateUidIdentifier("this");
var replaceSupers = new ReplaceSupers({
topLevelThisReference: thisExpr,
methodNode: node,
className: thisExpr,
isStatic: true,
scope: scope,
file: file
});
replaceSupers.replace();
if (replaceSupers.hasSuper) {
value.body.body.unshift(
t.variableDeclaration("var", [
t.variableDeclarator(thisExpr, t.thisExpression())
])
);
}
};

View File

@@ -1,76 +0,0 @@
"use strict";
var util = require("../../../util");
var t = require("../../../types");
exports.check = t.isRestElement;
var hasRest = function (node) {
return t.isRestElement(node.params[node.params.length - 1]);
};
exports.Function = function (node, parent, scope) {
if (!hasRest(node)) return;
var rest = node.params.pop().argument;
var argsId = t.identifier("arguments");
// otherwise `arguments` will be remapped in arrow functions
argsId._ignoreAliasFunctions = true;
var start = t.literal(node.params.length);
var key = scope.generateUidIdentifier("key");
var len = scope.generateUidIdentifier("len");
var arrKey = key;
var arrLen = len;
if (node.params.length) {
// this method has additional params, so we need to subtract
// the index of the current argument position from the
// position in the array that we want to populate
arrKey = t.binaryExpression("-", key, start);
// we need to work out the size of the array that we're
// going to store all the rest parameters
//
// we need to add a check to avoid constructing the array
// with <0 if there are less arguments than params as it'll
// cause an error
arrLen = t.conditionalExpression(
t.binaryExpression(">", len, start),
t.binaryExpression("-", len, start),
t.literal(0)
);
}
// support patterns
if (t.isPattern(rest)) {
var pattern = rest;
rest = scope.generateUidIdentifier("ref");
// let the destructuring transformer handle this
var restDeclar = t.variableDeclaration("var", [
t.variableDeclarator(pattern, rest)
]);
// retain evaluation position
restDeclar._blockHoist = node.params.length + 1;
node.body.body.unshift(restDeclar);
}
scope.assignTypeGeneric(rest.name, "Array");
var loop = util.template("rest", {
ARGUMENTS: argsId,
ARRAY_KEY: arrKey,
ARRAY_LEN: arrLen,
START: start,
ARRAY: rest,
KEY: key,
LEN: len,
});
loop._blockHoist = node.params.length + 1;
node.body.body.unshift(loop);
};

View File

@@ -1,21 +0,0 @@
"use strict";
var nameMethod = require("../../helpers/name-method");
var t = require("../../../types");
var clone = require("lodash/lang/clone");
exports.check = function (node) {
return t.isProperty(node) && (node.method || node.shorthand);
};
exports.Property = function (node, parent, scope, file) {
if (node.method) {
node.method = false;
nameMethod.property(node, file, scope);
}
if (node.shorthand) {
node.shorthand = false;
node.key = t.removeComments(clone(node.key));
}
};

View File

@@ -1,359 +0,0 @@
"use strict";
var reduceRight = require("lodash/collection/reduceRight");
var messages = require("../../../messages");
var flatten = require("lodash/array/flatten");
var util = require("../../../util");
var map = require("lodash/collection/map");
var t = require("../../../types");
function returnBlock(expr) {
return t.blockStatement([t.returnStatement(expr)]);
}
function TailCallTransformer(node, scope, file) {
this.hasTailRecursion = false;
this.needsArguments = false;
this.setsArguments = false;
this.needsThis = false;
this.ownerId = node.id;
this.vars = [];
this.scope = scope;
this.file = file;
this.node = node;
}
TailCallTransformer.prototype.getArgumentsId = function () {
return this.argumentsId = this.argumentsId || this.scope.generateUidIdentifier("arguments");
};
TailCallTransformer.prototype.getThisId = function () {
return this.thisId = this.thisId || this.scope.generateUidIdentifier("this");
};
TailCallTransformer.prototype.getLeftId = function () {
return this.leftId = this.leftId || this.scope.generateUidIdentifier("left");
};
TailCallTransformer.prototype.getFunctionId = function () {
return this.functionId = this.functionId || this.scope.generateUidIdentifier("function");
};
TailCallTransformer.prototype.getParams = function () {
var params = this.params;
if (!params) {
params = this.node.params;
this.paramDecls = [];
for (var i = 0; i < params.length; i++) {
var param = params[i];
if (!param._isDefaultPlaceholder) {
this.paramDecls.push(t.variableDeclarator(
param,
params[i] = this.scope.generateUidIdentifier("x")
));
}
}
}
return this.params = params;
};
TailCallTransformer.prototype.hasDeopt = function () {
// check if the ownerId has been reassigned, if it has then it's not safe to
// perform optimisations
var ownerIdInfo = this.scope.getBindingInfo(this.ownerId.name);
return ownerIdInfo && ownerIdInfo.reassigned;
};
TailCallTransformer.prototype.run = function () {
var scope = this.scope;
var node = this.node;
// only tail recursion can be optimized as for now, so we can skip anonymous
// functions entirely
var ownerId = this.ownerId;
if (!ownerId) return;
// traverse the function and look for tail recursion
scope.traverse(node, firstPass, this);
if (!this.hasTailRecursion) return;
if (this.hasDeopt()) {
this.file.logDeopt(node, messages.get("tailCallReassignmentDeopt"));
return;
}
//
scope.traverse(node, secondPass, this);
if (!this.needsThis || !this.needsArguments) {
scope.traverse(node, thirdPass, this);
}
var body = t.ensureBlock(node).body;
if (this.vars.length > 0) {
var declarations = flatten(map(this.vars, function (decl) {
return decl.declarations;
}, this));
var statement = reduceRight(declarations, function (expr, decl) {
return t.assignmentExpression("=", decl.id, expr);
}, t.identifier("undefined"));
body.unshift(t.expressionStatement(statement));
}
var paramDecls = this.paramDecls;
if (paramDecls.length > 0) {
body.unshift(t.variableDeclaration("var", paramDecls));
}
node.body = util.template("tail-call-body", {
THIS_ID: this.thisId,
ARGUMENTS_ID: this.argumentsId,
FUNCTION_ID: this.getFunctionId(),
BLOCK: node.body
});
var topVars = [];
if (this.needsThis) {
topVars.push(t.variableDeclarator(this.getThisId(), t.thisExpression()));
}
if (this.needsArguments || this.setsArguments) {
var decl = t.variableDeclarator(this.getArgumentsId());
if (this.needsArguments) {
decl.init = t.identifier("arguments");
}
topVars.push(decl);
}
var leftId = this.leftId;
if (leftId) {
topVars.push(t.variableDeclarator(leftId));
}
if (topVars.length > 0) {
node.body.body.unshift(t.variableDeclaration("var", topVars));
}
};
TailCallTransformer.prototype.subTransform = function (node) {
if (!node) return;
var handler = this["subTransform" + node.type];
if (handler) return handler.call(this, node);
};
TailCallTransformer.prototype.subTransformConditionalExpression = function (node) {
var callConsequent = this.subTransform(node.consequent);
var callAlternate = this.subTransform(node.alternate);
if (!callConsequent && !callAlternate) {
return;
}
// if ternary operator had tail recursion in value, convert to optimized if-statement
node.type = "IfStatement";
node.consequent = callConsequent ? t.toBlock(callConsequent) : returnBlock(node.consequent);
if (callAlternate) {
node.alternate = t.isIfStatement(callAlternate) ? callAlternate : t.toBlock(callAlternate);
} else {
node.alternate = returnBlock(node.alternate);
}
return [node];
};
TailCallTransformer.prototype.subTransformLogicalExpression = function (node) {
// only call in right-value of can be optimized
var callRight = this.subTransform(node.right);
if (!callRight) return;
// cache left value as it might have side-effects
var leftId = this.getLeftId();
var testExpr = t.assignmentExpression(
"=",
leftId,
node.left
);
if (node.operator === "&&") {
testExpr = t.unaryExpression("!", testExpr);
}
return [t.ifStatement(testExpr, returnBlock(leftId))].concat(callRight);
};
TailCallTransformer.prototype.subTransformSequenceExpression = function (node) {
var seq = node.expressions;
// only last element can be optimized
var lastCall = this.subTransform(seq[seq.length - 1]);
if (!lastCall) {
return;
}
// remove converted expression from sequence
// and convert to regular expression if needed
if (--seq.length === 1) {
node = seq[0];
}
return [t.expressionStatement(node)].concat(lastCall);
};
TailCallTransformer.prototype.subTransformCallExpression = function (node) {
var callee = node.callee, thisBinding, args;
if (t.isMemberExpression(callee, { computed: false }) && t.isIdentifier(callee.property)) {
switch (callee.property.name) {
case "call":
args = t.arrayExpression(node.arguments.slice(1));
break;
case "apply":
args = node.arguments[1] || t.identifier("undefined");
break;
default:
return;
}
thisBinding = node.arguments[0];
callee = callee.object;
}
// only tail recursion can be optimized as for now
if (!t.isIdentifier(callee) || !this.scope.bindingIdentifierEquals(callee.name, this.ownerId)) {
return;
}
this.hasTailRecursion = true;
if (this.hasDeopt()) return;
var body = [];
if (!t.isThisExpression(thisBinding)) {
body.push(t.expressionStatement(t.assignmentExpression(
"=",
this.getThisId(),
thisBinding || t.identifier("undefined")
)));
}
if (!args) {
args = t.arrayExpression(node.arguments);
}
var argumentsId = this.getArgumentsId();
var params = this.getParams();
body.push(t.expressionStatement(t.assignmentExpression(
"=",
argumentsId,
args
)));
var i, param;
if (t.isArrayExpression(args)) {
var elems = args.elements;
for (i = 0; i < elems.length && i < params.length; i++) {
param = params[i];
var elem = elems[i] || (elems[i] = t.identifier("undefined"));
if (!param._isDefaultPlaceholder) {
elems[i] = t.assignmentExpression("=", param, elem);
}
}
} else {
this.setsArguments = true;
for (i = 0; i < params.length; i++) {
param = params[i];
if (!param._isDefaultPlaceholder) {
body.push(t.expressionStatement(t.assignmentExpression(
"=",
param,
t.memberExpression(argumentsId, t.literal(i), true)
)));
}
}
}
body.push(t.continueStatement(this.getFunctionId()));
return body;
};
// looks for and replaces tail recursion calls
var firstPass = {
enter: function (node, parent, scope, state) {
if (t.isReturnStatement(node)) {
this.skip();
return state.subTransform(node.argument);
} else if (t.isTryStatement(parent)) {
if (node === parent.block) {
this.skip();
} else if (parent.finalizer && node !== parent.finalizer) {
this.skip();
}
} else if (t.isFunction(node)) {
this.skip();
} else if (t.isVariableDeclaration(node)) {
this.skip();
state.vars.push(node);
}
}
};
// hoists up function declarations, replaces `this` and `arguments` and marks
// them as needed
var secondPass = {
enter: function (node, parent, scope, state) {
if (t.isThisExpression(node)) {
state.needsThis = true;
return state.getThisId();
} else if (t.isReferencedIdentifier(node, parent, { name: "arguments" })) {
state.needsArguments = true;
return state.getArgumentsId();
} else if (t.isFunction(node)) {
this.skip();
if (t.isFunctionDeclaration(node)) {
node = t.variableDeclaration("var", [
t.variableDeclarator(node.id, t.toExpression(node))
]);
node._blockHoist = 2;
return node;
}
}
}
};
// optimizes recursion by removing `this` and `arguments` if they aren't used
var thirdPass = {
enter: function (node, parent, scope, state) {
if (!t.isExpressionStatement(node)) return;
var expr = node.expression;
if (!t.isAssignmentExpression(expr)) return;
if (!state.needsThis && expr.left === state.getThisId()) {
this.remove();
} else if (!state.needsArguments && expr.left === state.getArgumentsId() && t.isArrayExpression(expr.right)) {
return map(expr.right.elements, function (elem) {
return t.expressionStatement(elem);
});
}
}
};
exports.Function = function (node, parent, scope, file) {
var tailCall = new TailCallTransformer(node, scope, file);
tailCall.run();
};

View File

@@ -1,21 +0,0 @@
"use strict";
var rewritePattern = require("regexpu/rewrite-pattern");
var pull = require("lodash/array/pull");
var t = require("../../../types");
exports.check = function (node) {
return t.isLiteral(node) && node.regex && node.regex.flags.indexOf("u") >= 0;
};
exports.Literal = function (node) {
var regex = node.regex;
if (!regex) return;
var flags = regex.flags.split("");
if (regex.flags.indexOf("u") < 0) return;
pull(flags, "u");
regex.pattern = rewritePattern(regex.pattern, regex.flags);
regex.flags = flags.join("");
};

View File

@@ -1,36 +0,0 @@
"use strict";
var useStrict = require("../../helpers/use-strict");
var groupBy = require("lodash/collection/groupBy");
var flatten = require("lodash/array/flatten");
var values = require("lodash/object/values");
// Priority:
//
// - 0 We want this to be at the **very** bottom
// - 1 Default node position
// - 2 Priority over normal nodes
// - 3 We want this to be at the **very** top
exports.BlockStatement =
exports.Program = {
exit: function (node) {
var hasChange = false;
for (var i = 0; i < node.body.length; i++) {
var bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) hasChange = true;
}
if (!hasChange) return;
useStrict.wrap(node, function () {
var nodePriorities = groupBy(node.body, function (bodyNode) {
var priority = bodyNode._blockHoist;
if (priority == null) priority = 1;
if (priority === true) priority = 2;
return priority;
});
node.body = flatten(values(nodePriorities).reverse());
});
}
};

View File

@@ -1,5 +0,0 @@
exports.SequenceExpression = function (node) {
if (node.expressions.length === 1) {
return node.expressions[0];
}
};

View File

@@ -1,36 +0,0 @@
"use strict";
var useStrict = require("../../helpers/use-strict");
var t = require("../../../types");
exports.secondPass = true;
exports.BlockStatement =
exports.Program = function (node) {
if (!node._declarations) return;
var kinds = {};
var kind;
useStrict.wrap(node, function () {
for (var i in node._declarations) {
var declar = node._declarations[i];
kind = declar.kind || "var";
var declarNode = t.variableDeclarator(declar.id, declar.init);
if (!declar.init) {
kinds[kind] = kinds[kind] || [];
kinds[kind].push(declarNode);
} else {
node.body.unshift(t.variableDeclaration(kind, [declarNode]));
}
}
for (kind in kinds) {
node.body.unshift(t.variableDeclaration(kind, kinds[kind]));
}
});
node._declarations = null;
};

View File

@@ -1,9 +0,0 @@
var t = require("../../../types");
exports.optional = true;
exports.ExpressionStatement = function (node) {
if (t.isIdentifier(node.expression, { name: "debugger" })) {
this.remove();
}
};

View File

@@ -1,9 +0,0 @@
//var t = require("../../../types");
exports.optional = true;
exports.Scopable = function () {
//for (var name in scope.bindings) {
// scope.rename(name, scope.generateUidIdentifier("a").name);
//}
};

View File

@@ -1,14 +0,0 @@
"use strict";
var remapAsyncToGenerator = require("../../helpers/remap-async-to-generator");
var bluebirdCoroutines = require("./bluebird-coroutines");
exports.optional = true;
exports.manipulateOptions = bluebirdCoroutines.manipulateOptions;
exports.Function = function (node, parent, scope, file) {
if (!node.async || node.generator) return;
return remapAsyncToGenerator(node, file.addHelper("async-to-generator"), scope);
};

View File

@@ -1,20 +0,0 @@
"use strict";
var react = require("../../helpers/react");
var t = require("../../../types");
require("../../helpers/build-react-transformer")(exports, {
pre: function (state) {
var tagName = state.tagName;
var args = state.args;
if (react.isCompatTag(tagName)) {
args.push(t.literal(tagName));
} else {
args.push(state.tagExpr);
}
},
post: function (state) {
state.callee = t.memberExpression(t.identifier("React"), t.identifier("createElement"));
}
});

View File

@@ -1,15 +0,0 @@
"use strict";
var regenerator = require("regenerator-6to5");
var t = require("../../../types");
exports.check = function (node) {
return t.isFunction(node) && (node.async || node.generator);
};
exports.Program = {
enter: function (ast) {
regenerator.transform(ast);
this.stop();
}
};

View File

@@ -1,19 +0,0 @@
"use strict";
var useStrict = require("../../helpers/use-strict");
var t = require("../../../types");
exports.Program = function (program) {
if (!useStrict.has(program)) {
program.body.unshift(t.expressionStatement(t.literal("use strict")));
}
};
exports.FunctionDeclaration =
exports.FunctionExpression = function () {
this.skip();
};
exports.ThisExpression = function () {
return t.identifier("undefined");
};

View File

@@ -1,24 +0,0 @@
"use strict";
var messages = require("../../../messages");
var build = require("../../helpers/build-conditional-assignment-operator-transformer");
var t = require("../../../types");
exports.playground = true;
build(exports, {
is: function (node, file) {
var is = t.isAssignmentExpression(node) && node.operator === "||=";
if (is) {
var left = node.left;
if (!t.isMemberExpression(left) && !t.isIdentifier(left)) {
throw file.errorWithNode(left, messages.get("expectedMemberExpressionOrIdentifier"));
}
return true;
}
},
build: function (node) {
return t.unaryExpression("!", node, true);
}
});

View File

@@ -1,11 +0,0 @@
"use strict";
var t = require("../../../types");
exports.optional = true;
exports.Identifier = function (node, parent) {
if (node.name === "undefined" && t.isReferenced(node, parent)) {
return t.unaryExpression("void", t.literal(0), true);
}
};

View File

@@ -1,15 +0,0 @@
"use strict";
var messages = require("../../../messages");
var t = require("../../../types");
exports.check = t.isFor;
exports.ForInStatement =
exports.ForOfStatement = function (node, parent, scope, file) {
var left = node.left;
if (t.isVariableDeclaration(left)) {
var declar = left.declarations[0];
if (declar.init) throw file.errorWithNode(declar, messages.get("noAssignmentsInForHead"));
}
};

View File

@@ -1,14 +0,0 @@
"use strict";
var messages = require("../../../messages");
exports.check = function (node) {
return node.kind === "set";
};
exports.MethodDefinition =
exports.Property = function (node, parent, scope, file) {
if (node.kind === "set" && node.value.params.length !== 1) {
throw file.errorWithNode(node.value, messages.get("settersInvalidParamLength"));
}
};

View File

@@ -1,54 +0,0 @@
"use strict";
module.exports = TraversalContext;
var TraversalPath = require("./path");
var flatten = require("lodash/array/flatten");
var compact = require("lodash/array/compact");
function TraversalContext(scope, opts, state, parentPath) {
this.shouldFlatten = false;
this.parentPath = parentPath;
this.scope = scope;
this.state = state;
this.opts = opts;
}
TraversalContext.prototype.flatten = function () {
this.shouldFlatten = true;
};
TraversalContext.prototype.visitNode = function (node, obj, key) {
var iteration = new TraversalPath(this, node, obj, key);
return iteration.visit();
};
TraversalContext.prototype.visit = function (node, key) {
var nodes = node[key];
if (!nodes) return;
if (!Array.isArray(nodes)) {
return this.visitNode(node, node, key);
}
// nothing to traverse!
if (nodes.length === 0) {
return;
}
for (var i = 0; i < nodes.length; i++) {
if (nodes[i] && this.visitNode(node, nodes, i)) {
return true;
}
}
if (this.shouldFlatten) {
node[key] = flatten(node[key]);
if (key === "body") {
// we can safely compact this
node[key] = compact(node[key]);
}
}
};

View File

@@ -1,156 +0,0 @@
"use strict";
module.exports = TraversalPath;
/* jshint maxparams:7 */
var traverse = require("./index");
var includes = require("lodash/collection/includes");
var Scope = require("./scope");
var t = require("../types");
function TraversalPath(context, parent, obj, key) {
this.shouldRemove = false;
this.shouldSkip = false;
this.shouldStop = false;
this.parentPath = context.parentPath;
this.context = context;
this.state = this.context.state;
this.opts = this.context.opts;
this.key = key;
this.obj = obj;
this.parent = parent;
this.scope = TraversalPath.getScope(this.getNode(), parent, context.scope);
this.state = context.state;
}
TraversalPath.prototype.remove = function () {
this.shouldRemove = true;
this.shouldSkip = true;
};
TraversalPath.prototype.skip = function () {
this.shouldSkip = true;
};
TraversalPath.prototype.stop = function () {
this.shouldStop = true;
this.shouldSkip = true;
};
TraversalPath.prototype.flatten = function () {
this.context.flatten();
};
TraversalPath.getScope = function (node, parent, scope) {
var ourScope = scope;
// we're entering a new scope so let's construct it!
if (t.isScope(node, parent)) {
ourScope = new Scope(node, parent, scope);
}
return ourScope;
};
TraversalPath.prototype.maybeRemove = function () {
if (this.shouldRemove) {
this.setNode(null);
this.flatten();
}
};
TraversalPath.prototype.setNode = function (val) {
return this.obj[this.key] = val;
};
TraversalPath.prototype.getNode = function () {
return this.obj[this.key];
};
TraversalPath.prototype.replaceNode = function (replacement) {
var isArray = Array.isArray(replacement);
// inherit comments from original node to the first replacement node
var inheritTo = replacement;
if (isArray) inheritTo = replacement[0];
if (inheritTo) t.inheritsComments(inheritTo, this.getNode());
// replace the node
this.setNode(replacement);
var file = this.scope && this.scope.file;
if (file) {
if (isArray) {
for (var i = 0; i < replacement.length; i++) {
file.checkNode(replacement[i], this.scope);
}
} else {
file.checkNode(replacement, this.scope);
}
}
// we're replacing a statement or block node with an array of statements so we better
// ensure that it's a block
if (isArray) {
if (includes(t.STATEMENT_OR_BLOCK_KEYS, this.key) && !t.isBlockStatement(this.obj)) {
t.ensureBlock(this.obj, this.key);
}
this.flatten();
}
};
TraversalPath.prototype.call = function (key) {
var node = this.getNode();
if (!node) return;
var opts = this.opts;
var fn = opts[key] || opts;
if (opts[node.type]) fn = opts[node.type][key] || fn;
var replacement = fn.call(this, node, this.parent, this.scope, this.state);
if (replacement) {
this.replaceNode(replacement);
node = replacement;
}
this.maybeRemove();
return node;
};
TraversalPath.prototype.visit = function () {
var opts = this.opts;
var node = this.getNode();
// type is blacklisted
if (opts.blacklist && opts.blacklist.indexOf(node.type) > -1) {
return;
}
this.call("enter");
if (this.shouldSkip) {
return this.shouldStop;
}
node = this.getNode();
if (Array.isArray(node)) {
// traverse over these replacement nodes we purposely don't call exitNode
// as the original node has been destroyed
for (var i = 0; i < node.length; i++) {
traverse.node(node[i], opts, this.scope, this.state, this);
}
} else {
traverse.node(node, opts, this.scope, this.state, this);
this.call("exit");
}
return this.shouldStop;
};

View File

@@ -1,646 +0,0 @@
"use strict";
module.exports = Scope;
var includes = require("lodash/collection/includes");
var traverse = require("./index");
var defaults = require("lodash/object/defaults");
var messages = require("../messages");
var globals = require("globals");
var flatten = require("lodash/array/flatten");
var extend = require("lodash/object/extend");
var object = require("../helpers/object");
var each = require("lodash/collection/each");
var t = require("../types");
/**
* This searches the current "scope" and collects all references/bindings
* within.
*
* @param {Node} block
* @param {Node} parentBlock
* @param {Scope} [parent]
* @param {File} [file]
*/
function Scope(block, parentBlock, parent, file) {
this.parent = parent;
this.file = parent ? parent.file : file;
this.parentBlock = parentBlock;
this.block = block;
this.crawl();
}
Scope.defaultDeclarations = flatten([globals.builtin, globals.browser, globals.node].map(Object.keys));
/**
* Description
*
* @param {Object} node
* @param {Object} opts
* @param [state]
*/
Scope.prototype.traverse = function (node, opts, state) {
traverse(node, opts, this, state);
};
/**
* Description
*
* @param {String} [name="temp"]
*/
Scope.prototype.generateTemp = function (name) {
var id = this.generateUidIdentifier(name || "temp");
this.push({
key: id.name,
id: id
});
return id;
};
/**
* Description
*
* @param {String} name
*/
Scope.prototype.generateUidIdentifier = function (name) {
var id = t.identifier(this.generateUid(name));
this.getFunctionParent().registerBinding("uid", id);
return id;
};
/**
* Description
*
* @param {String} name
*/
Scope.prototype.generateUid = function (name) {
name = t.toIdentifier(name).replace(/^_+/, "");
var uid;
var i = 0;
do {
uid = this._generateUid(name, i);
i++;
} while (this.hasBinding(uid) || this.hasGlobal(uid));
return uid;
};
Scope.prototype._generateUid = function (name, i) {
var id = name;
if (i > 1) id += i;
return "_" + id;
};
/*
* Description
*
* @param {Object} parent
* @returns {Object}
*/
Scope.prototype.generateUidBasedOnNode = function (parent) {
var node = parent;
if (t.isAssignmentExpression(parent)) {
node = parent.left;
} else if (t.isVariableDeclarator(parent)) {
node = parent.id;
} else if (t.isProperty(node)) {
node = node.key;
}
var parts = [];
var add = function (node) {
if (t.isMemberExpression(node)) {
add(node.object);
add(node.property);
} else if (t.isIdentifier(node)) {
parts.push(node.name);
} else if (t.isLiteral(node)) {
parts.push(node.value);
} else if (t.isCallExpression(node)) {
add(node.callee);
}
};
add(node);
var id = parts.join("$");
id = id.replace(/^_/, "") || "ref";
return this.generateUidIdentifier(id);
};
/**
* Description
*
* @param {Object} node
* @returns {Object}
*/
Scope.prototype.generateTempBasedOnNode = function (node) {
if (t.isIdentifier(node) && this.hasBinding(node.name)) {
return null;
}
var id = this.generateUidBasedOnNode(node);
this.push({
key: id.name,
id: id
});
return id;
};
Scope.prototype.checkBlockScopedCollisions = function (kind, name, id) {
var local = this.getOwnBindingInfo(name);
if (!local) return;
if (kind === "param") return;
if (kind === "hoisted" && local.kind === "let") return;
if (local.kind === "let" || local.kind === "const" || local.kind === "module") {
throw this.file.errorWithNode(id, messages.get("scopeDuplicateDeclaration", name), TypeError);
}
};
Scope.prototype.rename = function (oldName, newName) {
newName = newName || this.generateUidIdentifier(oldName).name;
var info = this.getBindingInfo(oldName);
if (!info) return;
var binding = info.identifier;
var scope = info.scope;
scope.traverse(scope.block, {
enter: function (node, parent, scope) {
if (t.isReferencedIdentifier(node, parent) && node.name === oldName) {
node.name = newName;
} else if (t.isDeclaration(node)) {
var ids = t.getBindingIdentifiers(node);
for (var name in ids) {
if (name === oldName) ids[name].name = newName;
}
} else if (t.isScope(node, parent)) {
if (!scope.bindingIdentifierEquals(oldName, binding)) {
this.skip();
}
}
}
});
this.clearOwnBinding(oldName);
scope.bindings[newName] = info;
binding.name = newName;
};
Scope.prototype.inferType = function (node) {
var target;
if (t.isVariableDeclarator(node)) {
target = node.init;
}
if (t.isArrayExpression(target)) {
return t.genericTypeAnnotation(t.identifier("Array"));
}
if (t.isObjectExpression(target)) {
return;
}
if (t.isLiteral(target)) {
return;
}
if (t.isCallExpression(target) && t.isIdentifier(target.callee)) {
var funcInfo = this.getBindingInfo(target.callee.name);
if (funcInfo) {
var funcNode = funcInfo.node;
return !funcInfo.reassigned && t.isFunction(funcNode) && node.returnType;
}
}
if (t.isIdentifier(target)) {
return;
}
};
Scope.prototype.isTypeGeneric = function (name, genericName) {
var info = this.getBindingInfo(name);
if (!info) return false;
var type = info.typeAnnotation;
return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName });
};
Scope.prototype.assignTypeGeneric = function (name, type) {
this.assignType(name, t.genericTypeAnnotation(t.identifier(type)));
};
Scope.prototype.assignType = function (name, type) {
var info = this.getBindingInfo(name);
if (!info) return;
info.identifier.typeAnnotation = info.typeAnnotation = type;
};
Scope.prototype.getTypeAnnotation = function (name, id, node) {
var info = {
annotation: null,
inferred: false
};
var type;
if (id.typeAnnotation) {
type = id.typeAnnotation;
}
if (!type) {
info.inferred = true;
type = this.inferType(node);
}
if (type) {
if (t.isTypeAnnotation(type)) type = type.typeAnnotation;
info.annotation = type;
}
return info;
};
Scope.prototype.toArray = function (node, i) {
var file = this.file;
if (t.isIdentifier(node) && this.isTypeGeneric(node.name, "Array")) {
return node;
}
if (t.isArrayExpression(node)) {
return node;
}
if (t.isIdentifier(node, { name: "arguments" })) {
return t.callExpression(t.memberExpression(file.addHelper("slice"), t.identifier("call")), [node]);
}
var helperName = "to-array";
var args = [node];
if (i === true) {
helperName = "to-consumable-array";
} else if (i) {
args.push(t.literal(i));
helperName = "sliced-to-array";
}
return t.callExpression(file.addHelper(helperName), args);
};
Scope.prototype.clearOwnBinding = function (name) {
delete this.bindings[name];
};
Scope.prototype.registerDeclaration = function (node) {
if (t.isFunctionDeclaration(node)) {
this.registerBinding("hoisted", node);
} else if (t.isVariableDeclaration(node)) {
for (var i = 0; i < node.declarations.length; i++) {
this.registerBinding(node.kind, node.declarations[i]);
}
} else if (t.isClassDeclaration(node)) {
this.registerBinding("let", node);
} else if (t.isImportDeclaration(node) || t.isExportDeclaration(node)) {
this.registerBinding("module", node);
} else {
this.registerBinding("unknown", node);
}
};
Scope.prototype.registerBindingReassignment = function (node) {
var ids = t.getBindingIdentifiers(node);
for (var name in ids) {
var info = this.getBindingInfo(name);
if (info) {
info.reassigned = true;
if (info.typeAnnotationInferred) {
// destroy the inferred typeAnnotation
info.typeAnnotation = null;
}
}
}
};
Scope.prototype.registerBinding = function (kind, node) {
if (!kind) throw new ReferenceError("no `kind`");
var ids = t.getBindingIdentifiers(node);
for (var name in ids) {
var id = ids[name];
this.checkBlockScopedCollisions(kind, name, id);
var typeInfo = this.getTypeAnnotation(name, id, node);
this.bindings[name] = {
typeAnnotationInferred: typeInfo.inferred,
typeAnnotation: typeInfo.annotation,
reassigned: false,
identifier: id,
scope: this,
node: node,
kind: kind
};
}
};
Scope.prototype.registerVariableDeclaration = function (declar) {
var declars = declar.declarations;
for (var i = 0; i < declars.length; i++) {
this.registerBinding(declars[i], declar.kind);
}
};
var functionVariableVisitor = {
enter: function (node, parent, scope, state) {
if (t.isFor(node)) {
each(t.FOR_INIT_KEYS, function (key) {
var declar = node[key];
if (t.isVar(declar)) state.scope.registerBinding("var", declar);
});
}
// this block is a function so we'll stop since none of the variables
// declared within are accessible
if (t.isFunction(node)) return this.skip();
// function identifier doesn't belong to this scope
if (state.blockId && node === state.blockId) return;
// delegate block scope handling to the `blockVariableVisitor`
if (t.isBlockScoped(node)) return;
// this will be hit again once we traverse into it after this iteration
if (t.isExportDeclaration(node) && t.isDeclaration(node.declaration)) return;
// we've ran into a declaration!
if (t.isDeclaration(node)) state.scope.registerDeclaration(node);
}
};
Scope.prototype.addGlobal = function (node) {
this.globals[node.name] = node;
};
Scope.prototype.hasGlobal = function (name) {
var scope = this;
do {
if (scope.globals[name]) return true;
} while (scope = scope.parent);
return false;
};
var programReferenceVisitor = {
enter: function (node, parent, scope, state) {
if (t.isReferencedIdentifier(node, parent) && !scope.hasBinding(node.name)) {
state.addGlobal(node);
} else if (t.isLabeledStatement(node)) {
state.addGlobal(node);
} else if (t.isAssignmentExpression(node) || t.isUpdateExpression(node) || (t.isUnaryExpression(node) && node.operator === "delete")) {
scope.registerBindingReassignment(node);
}
}
};
var blockVariableVisitor = {
enter: function (node, parent, scope, state) {
if (t.isFunctionDeclaration(node) || t.isBlockScoped(node)) {
state.registerDeclaration(node);
} else if (t.isScope(node, parent)) {
this.skip();
}
}
};
Scope.prototype.crawl = function () {
var block = this.block;
var i;
//
var info = block._scopeInfo;
if (info) {
extend(this, info);
return;
}
info = block._scopeInfo = {
bindings: object(),
globals: object()
};
extend(this, info);
// ForStatement - left, init
if (t.isLoop(block)) {
for (i = 0; i < t.FOR_INIT_KEYS.length; i++) {
var node = block[t.FOR_INIT_KEYS[i]];
if (t.isBlockScoped(node)) this.registerBinding("let", node);
}
if (t.isBlockStatement(block.body)) {
block = block.body;
}
}
// FunctionExpression - id
if (t.isFunctionExpression(block) && block.id) {
if (!t.isProperty(this.parentBlock, { method: true })) {
this.registerBinding("var", block.id);
}
}
// Function - params, rest
if (t.isFunction(block)) {
for (i = 0; i < block.params.length; i++) {
this.registerBinding("param", block.params[i]);
}
this.traverse(block.body, blockVariableVisitor, this);
}
// Program, BlockStatement, Function - let variables
if (t.isBlockStatement(block) || t.isProgram(block)) {
this.traverse(block, blockVariableVisitor, this);
}
// CatchClause - param
if (t.isCatchClause(block)) {
this.registerBinding("let", block.param);
}
// ComprehensionExpression - blocks
if (t.isComprehensionExpression(block)) {
this.registerBinding("let", block);
}
// Program, Function - var variables
if (t.isProgram(block) || t.isFunction(block)) {
this.traverse(block, functionVariableVisitor, {
blockId: block.id,
scope: this
});
}
// Program
if (t.isProgram(block)) {
this.traverse(block, programReferenceVisitor, this);
}
};
/**
* Description
*
* @param {Object} opts
*/
Scope.prototype.push = function (opts) {
var block = this.block;
if (t.isFor(block) || t.isCatchClause(block) || t.isFunction(block)) {
t.ensureBlock(block);
block = block.body;
}
if (t.isBlockStatement(block) || t.isProgram(block)) {
block._declarations = block._declarations || {};
block._declarations[opts.key] = {
kind: opts.kind,
id: opts.id,
init: opts.init
};
} else {
throw new TypeError("cannot add a declaration here in node type " + block.type);
}
};
/**
* Walk up the scope tree until we hit either a Function or reach the
* very top and hit Program.
*/
Scope.prototype.getFunctionParent = function () {
var scope = this;
while (scope.parent && !t.isFunction(scope.block)) {
scope = scope.parent;
}
return scope;
};
/**
* Walks the scope tree and gathers **all** bindings.
*
* @returns {Object}
*/
Scope.prototype.getAllBindings = function () {
var ids = object();
var scope = this;
do {
defaults(ids, scope.bindings);
scope = scope.parent;
} while (scope);
return ids;
};
/**
* Walks the scope tree and gathers all declarations of `kind`.
*
* @param {String} kind
* @returns {Object}
*/
Scope.prototype.getAllBindingsOfKind = function (kind) {
var ids = object();
var scope = this;
do {
for (var name in scope.bindings) {
var binding = scope.bindings[name];
if (binding.kind === kind) ids[name] = binding;
}
scope = scope.parent;
} while (scope);
return ids;
};
// misc
Scope.prototype.bindingIdentifierEquals = function (name, node) {
return this.getBindingIdentifier(name) === node;
};
// get
Scope.prototype.getBindingInfo = function (name) {
var scope = this;
do {
var binding = scope.getOwnBindingInfo(name);
if (binding) return binding;
} while (scope = scope.parent);
};
Scope.prototype.getOwnBindingInfo = function (name) {
return this.bindings[name];
};
Scope.prototype.getBindingIdentifier = function (name) {
var info = this.getBindingInfo(name);
return info && info.identifier;
};
Scope.prototype.getOwnBindingIdentifier = function (name) {
var binding = this.bindings[name];
return binding && binding.identifier;
};
// has
Scope.prototype.hasOwnBinding = function (name) {
return !!this.getOwnBindingInfo(name);
};
Scope.prototype.hasBinding = function (name) {
if (!name) return false;
if (this.hasOwnBinding(name)) return true;
if (this.parentHasBinding(name)) return true;
if (includes(Scope.defaultDeclarations, name)) return true;
return false;
};
Scope.prototype.parentHasBinding = function (name) {
return this.parent && this.parent.hasBinding(name);
};

View File

@@ -1,168 +0,0 @@
"use strict";
require("./patch");
var cloneDeep = require("lodash/lang/cloneDeep");
var contains = require("lodash/collection/contains");
var traverse = require("./traversal");
var isNumber = require("lodash/lang/isNumber");
var isString = require("lodash/lang/isString");
var isRegExp = require("lodash/lang/isRegExp");
var isEmpty = require("lodash/lang/isEmpty");
var parse = require("./helpers/parse");
var debug = require("debug/node");
var path = require("path");
var util = require("util");
var each = require("lodash/collection/each");
var has = require("lodash/object/has");
var fs = require("fs");
var t = require("./types");
exports.inherits = util.inherits;
exports.debug = debug("6to5");
exports.canCompile = function (filename, altExts) {
var exts = altExts || exports.canCompile.EXTENSIONS;
var ext = path.extname(filename);
return contains(exts, ext);
};
exports.canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"];
exports.normalisePathSeparator = function (filename) {
return filename.replace(/\\/g, "/");
};
exports.isInteger = function (i) {
return isNumber(i) && i % 1 === 0;
};
exports.resolve = function (loc) {
try {
return require.resolve(loc);
} catch (err) {
return null;
}
};
exports.trimRight = function (str) {
return str.replace(/[\n\s]+$/g, "");
};
exports.list = function (val) {
return val ? val.split(",") : [];
};
exports.regexify = function (val) {
if (!val) return new RegExp(/.^/);
if (Array.isArray(val)) val = val.join("|");
if (isString(val)) return new RegExp(val);
if (isRegExp(val)) return val;
throw new TypeError("illegal type for regexify");
};
exports.arrayify = function (val) {
if (!val) return [];
if (isString(val)) return exports.list(val);
if (Array.isArray(val)) return val;
throw new TypeError("illegal type for arrayify");
};
exports.isAbsolute = function (loc) {
if (!loc) return false;
if (loc[0] === "/") return true; // unix
if (loc[1] === ":" && loc[2] === "\\") return true; // windows
return false;
};
exports.sourceMapToComment = function (map) {
var json = JSON.stringify(map);
var base64 = new Buffer(json).toString("base64");
return "//# sourceMappingURL=data:application/json;base64," + base64;
};
var templateVisitor = {
enter: function (node, parent, scope, nodes) {
if (t.isExpressionStatement(node)) {
node = node.expression;
}
if (t.isIdentifier(node) && has(nodes, node.name)) {
this.skip();
return nodes[node.name];
}
}
};
exports.template = function (name, nodes, keepExpression) {
var template = exports.templates[name];
if (!template) throw new ReferenceError("unknown template " + name);
if (nodes === true) {
keepExpression = true;
nodes = null;
}
template = cloneDeep(template);
if (!isEmpty(nodes)) {
traverse(template, templateVisitor, null, nodes);
}
if (template.body.length > 1) return template.body;
var node = template.body[0];
if (!keepExpression && t.isExpressionStatement(node)) {
return node.expression;
} else {
return node;
}
};
exports.repeat = function (width, cha) {
cha = cha || " ";
var result = "";
for (var i = 0; i < width; i++) {
result += cha;
}
return result;
};
exports.parseTemplate = function (loc, code) {
var ast = parse({ filename: loc }, code).program;
return traverse.removeProperties(ast);
};
var loadTemplates = function () {
var templates = {};
var templatesLoc = __dirname + "/transformation/templates";
if (!fs.existsSync(templatesLoc)) {
throw new Error("no templates directory - this is most likely the " +
"result of a broken `npm publish`. Please report to " +
"https://github.com/6to5/6to5/issues");
}
each(fs.readdirSync(templatesLoc), function (name) {
if (name[0] === ".") return;
var key = path.basename(name, path.extname(name));
var loc = templatesLoc + "/" + name;
var code = fs.readFileSync(loc, "utf8");
templates[key] = exports.parseTemplate(loc, code);
});
return templates;
};
try {
exports.templates = require("../../templates.json");
} catch (err) {
if (err.code !== "MODULE_NOT_FOUND") throw err;
exports.templates = loadTemplates();
}

View File

@@ -1,20 +1,22 @@
{
"name": "6to5",
"name": "babel",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "3.6.3",
"version": "4.7.5",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://6to5.org/",
"repository": "6to5/6to5",
"homepage": "https://babeljs.io/",
"repository": "babel/babel",
"preferGlobal": true,
"main": "lib/6to5/api/node.js",
"main": "lib/babel/api/node.js",
"browser": {
"./lib/6to5/api/register/node.js": "./lib/6to5/api/register/browser.js"
"./lib/babel/api/register/node.js": "./lib/babel/api/register/browser.js"
},
"bin": {
"6to5": "./bin/6to5/index.js",
"6to5-minify": "./bin/6to5-minify",
"6to5-node": "./bin/6to5-node",
"6to5-runtime": "./bin/6to5-runtime"
"6to5": "./bin/deprecated/6to5",
"6to5-node": "./bin/deprecated/6to5-node",
"6to5-runtime": "./bin/deprecated/6to5-runtime",
"babel": "./bin/babel/index.js",
"babel-node": "./bin/babel-node",
"babel-external-helpers": "./bin/babel-external-helpers"
},
"keywords": [
"harmony",
@@ -26,49 +28,56 @@
"es6",
"transpile",
"transpiler",
"6to5"
"6to5",
"babel"
],
"scripts": {
"bench": "make bench",
"test": "make test"
},
"dependencies": {
"acorn-6to5": "0.11.1-31",
"ast-types": "~0.6.1",
"chalk": "^0.5.1",
"chokidar": "0.12.6",
"commander": "2.6.0",
"core-js": "^0.5.2",
"acorn-babel": "0.11.1-37",
"ast-types": "~0.7.0",
"chalk": "^1.0.0",
"chokidar": "^0.12.6",
"commander": "^2.6.0",
"convert-source-map": "^0.5.0",
"core-js": "^0.6.1",
"debug": "^2.1.1",
"detect-indent": "3.0.0",
"estraverse": "1.9.1",
"esutils": "1.1.6",
"fs-readdir-recursive": "0.1.0",
"globals": "^5.1.0",
"js-tokenizer": "1.3.3",
"lodash": "3.0.0",
"output-file-sync": "1.1.0",
"private": "0.1.6",
"regenerator-6to5": "0.8.10-1",
"regexpu": "1.1.0",
"roadrunner": "1.0.4",
"source-map": "0.1.43",
"source-map-support": "0.2.9",
"supports-color": "1.2.0",
"useragent": "^2.1.5"
"detect-indent": "^3.0.0",
"estraverse": "^1.9.1",
"esutils": "^1.1.6",
"fs-readdir-recursive": "^0.1.0",
"globals": "^6.2.0",
"is-integer": "^1.0.4",
"js-tokens": "1.0.0",
"leven": "^1.0.1",
"line-numbers": "0.2.0",
"lodash": "^3.2.0",
"output-file-sync": "^1.1.0",
"path-is-absolute": "^1.0.0",
"private": "^0.1.6",
"regenerator-babel": "0.8.13-2",
"regexpu": "^1.1.2",
"repeating": "^1.1.2",
"shebang-regex": "^1.0.0",
"slash": "^1.0.0",
"source-map": "^0.4.0",
"source-map-support": "^0.2.9",
"to-fast-properties": "^1.0.0",
"trim-right": "^1.0.0"
},
"devDependencies": {
"6to5": "3.6.0",
"browserify": "8.1.1",
"chai": "1.10.0",
"esvalid": "1.1.0",
"istanbul": "0.3.5",
"jscs": "1.10.0",
"jshint": "2.6.0",
"jshint-stylish": "1.0.0",
"matcha": "0.6.0",
"mocha": "2.1.0",
"rimraf": "2.2.8",
"uglify-js": "2.4.16"
"babel": "4.6.0",
"browserify": "^9.0.3",
"chai": "^2.0.0",
"eslint": "^0.15.1",
"babel-eslint": "^1.0.1",
"esvalid": "^1.1.0",
"istanbul": "^0.3.5",
"matcha": "^0.6.0",
"mocha": "^2.1.0",
"rimraf": "^2.2.8",
"uglify-js": "^2.4.16"
}
}

Some files were not shown because too many files have changed in this diff Show More