grunt lib remove
parent
c451952cd3
commit
83716d6656
|
@ -0,0 +1,253 @@
|
|||
#KODexplorer (http://kalcaddle.com/)
|
||||
###ver2.1(2014.4.2) power by warlee
|
||||
商业版授权请联系:QQ:kalcaddle@qq.com
|
||||
|
||||
是什么:
|
||||
Kodexplorer为千帆网络工作室开发的一款服务器文件管理程序。
|
||||
可用于服务器文件管理,支持图片、音乐、视频预览。在线解压缩。
|
||||
支持几乎所有编程语言的在线编辑(高亮,多光标编辑.堪比本地的sublime)
|
||||
中文编码全面兼容,文件编辑自动适配。
|
||||
及其便捷的快捷键支持,让你拥有本地化的体验
|
||||
全面采用Ajax+Json进行数据通信,毫秒级的响应速度;
|
||||
全平台兼容性:Win Linux Mac (Apache、Nginx、IIS)
|
||||
使用场景:
|
||||
你可以用它来管理你的服务器(备份,在线解压缩,版本发布....)
|
||||
你可以把他当做管理linux的一个操作系统界面
|
||||
可以用来作为私有云存储系统,存储你的文件...
|
||||
当然你也可以用来分享文件
|
||||
更多场景等你来挖掘!……
|
||||
|
||||
## 请尽量不要使用第三方修改版本,放置被植入恶意代码或后门
|
||||
## 觉得程序好用的话请尽量购买商业版
|
||||
|
||||
------------------【使用说明】------------------
|
||||
管理员: admin/admin
|
||||
普通用户:demo/demo
|
||||
游客用户:guest/guest
|
||||
|
||||
【如何使用】下载程序,上传到你的服务器路径下,解压。访问即可,体验超便捷的服务吧!
|
||||
【关于上传问题】 程序没有做任何限制,如果需要上传大文件,则修改php.ini:upload_max_filesize = 1000M post_max_size = 1000M
|
||||
【关于解压缩问题】 程序不做任何限制,如若失败请设置php内存限制。memory_limit 1000M
|
||||
【关于兼容性】建议使用chrome firefox ie9+ 体验更完整。ie8以下基本上不做兼容处理。chrome才支持文件夹拖拽上传。
|
||||
【文件打开】office文件在线预览功能,服务器必须在公网(外部能访问该服务器)
|
||||
--------------------------------------------
|
||||
|
||||
|
||||
ver2.1 `2014/4/2`
|
||||
=====================
|
||||
##update:
|
||||
文件夹拖拽上传,完美解决(保持原始目录结构)
|
||||
解压缩优化;解压中文问题。解压缩整体速度
|
||||
树目录增加快捷键支持(上下、左右展开树目录;复制、粘贴、剪切、删除、打开、搜索、新建文件(夹)、)
|
||||
pdf预览支持
|
||||
mac快捷键 ctrl 一一对应command
|
||||
音乐播放器和视频播放器相互独立
|
||||
图片懒加载、图片较多的情况下只加载首屏图片缩略图;
|
||||
编辑文件打开出错,自动关闭标签;文件打开20M限制(大于20M则不处理,浏览器会卡死)
|
||||
标签关闭提示:检测是否有未保存文件,文件修改实时修改是否修修改的按钮状态
|
||||
##fix bug:(bug解决和程序优化)
|
||||
文本文件编辑 文件名含有url编码则出错bug
|
||||
右键菜单在最下面时,右键位置重叠导致点击菜单问题
|
||||
编辑器打开文件时光标问题,处理:移动到行尾;编辑器enter建不显示自动提示
|
||||
iframe 打开url 优化。解决canvas问题
|
||||
文件编辑器,载入loading去掉
|
||||
删除错误时,或上传错误时也刷新目录。删除提示颜色错误
|
||||
对话框右键 点击右键菜单隐藏修复
|
||||
手机端 touch =双击
|
||||
文件列表 explorer 右键 不清除选才·
|
||||
树目录中文展开问题。
|
||||
ie 重命名状态textarea不可选则问题
|
||||
修复mac 下 ctrl连选出现右键菜单。
|
||||
ie 树目录右键兼容性
|
||||
|
||||
|
||||
ver2.0 `2014/3/2`
|
||||
=====================
|
||||
##fix bug:(bug解决和程序优化)
|
||||
body右键屏蔽(保留input、textarea)
|
||||
重命名&新建时 右键(编辑内容系统菜单)
|
||||
对话框 不显示边框(位移处理,opacity:0)
|
||||
esc 退出程序 屏蔽该功能。
|
||||
关闭播放器,还在播放bug
|
||||
增加资源管理器任务栏。任务栏加入右键功能。
|
||||
对话框增加右键功能
|
||||
guest [三类用户 root/default/guest] guest登陆处加链接。20min
|
||||
打包程序[update user_add,admin/demo; 删除webuploader.js thumb less]
|
||||
编辑添加应用权限只能是root用户才可以。
|
||||
保存文件不可写提示!
|
||||
解压缩结果提示。(对话框)
|
||||
upload dialog display
|
||||
root登陆 目录修改为服务器路径
|
||||
artdialog 已经打开的窗口 (设了id) 最小化时,再次打开则显示
|
||||
最小化窗口后,再次打开 dialog display (setting-display)
|
||||
上传进度加入大小
|
||||
上传窗口关闭,自动停止所有上传队列
|
||||
拖拽后,更新上传地址为当前地址。(之前上传队列也会这样。bug)
|
||||
root用户非服务器路径下文件预览(图片、mp3、视频、html、swf、……php代理输出文件内容,http方式)
|
||||
对话框最小化或关闭,重置最大index为焦点窗口
|
||||
图片缩略图生成:小于5k则不生成(直接输出)
|
||||
加载文件列表改为异步方式,数据返回采用回调函数方式。增强体验
|
||||
选中优化,文件&文件夹重命名、文件&文件夹新建 后自动选中。(f5增加回调。);
|
||||
选中保持,选中后如果调整排序等等,保持选中状态。
|
||||
上传文件选中当前。
|
||||
f5改为异步(加入mask loading) 优化文件夹打开体验
|
||||
键盘按键选中文件 增加字符搜索定位功能(单个字符,增加到多个字符选中。两次响应直接延迟250ms)
|
||||
幻灯片播放[优化成fancybox或者 重写动画部分、打开时关不掉问题]
|
||||
编辑器backspace、delete时不提示。
|
||||
编辑器,增加选中效果
|
||||
增加不自动提示功能,配置项作为全局配置。影响后续建立的文件。选中标记状态。
|
||||
更换桌面背景图片【load后替换】
|
||||
更换主题【css load 后载入】
|
||||
删除。不清除选中。提前准备数据
|
||||
构建打包,合并压缩。添加版本、版权
|
||||
自动升级(本地记录版本,服务器js调用 参数 url、version;忽略此版本。cookie。统计用户)
|
||||
|
||||
|
||||
ver2.0debug `2014/3/2`
|
||||
=====================
|
||||
##fix bug:(bug解决和程序优化)
|
||||
优化文件打开处理
|
||||
文件&文件夹:含有%、+号的处理(显示不出等问题,encoenURIComponent——rawurldecode)
|
||||
文件下载,支持大文件下载、断点续传。
|
||||
解决更改排序方式后 ——对应右键菜单不同步问题。
|
||||
优化右键更改列表状态,同步保存配置到服务端。
|
||||
文件浏览器打开(a点击新窗口跳转,a不支持click,用子元素冒泡来实现点击)
|
||||
优化配置文件存储方案。直接由前端操作后端key,value
|
||||
修复添加收藏夹问题(已打开设置窗口再添加失败问题)
|
||||
修复树目录中文文件名bug
|
||||
优化pic图片幻灯片播放
|
||||
优化新建文件&文件夹 清空选择状态
|
||||
对话框组件 ie8 优化;tips不显示任务栏;
|
||||
优化地址栏过长编辑状态问题
|
||||
优化新建、重命名文件(夹) 高度自适应问题
|
||||
firefox ctrl+s 系统对话框屏蔽
|
||||
树目录:收藏夹优化(右键绑定);右键操作优化,拖拽优化(文件管理&编辑器)
|
||||
收藏夹优化(右键 >编辑删除)
|
||||
##update:
|
||||
###新增功能
|
||||
多用户、权限控制:
|
||||
可以建立权限组,将功能分配给权限组
|
||||
添加用户,选择所属的权限组。
|
||||
权限按功能划分成颗粒,可以任意配置,例如普通使用者、游客等
|
||||
搜索:支持递归搜索,可选择是否搜索文件内容。
|
||||
增加桌面自定义壁纸。
|
||||
皮肤优化 ok 多色彩支持。
|
||||
应用商店,root用户可以管理应用。安装、修改、删除。普通用户可以安装应用。
|
||||
应用添加了图标。对应右键功能。
|
||||
office文档在线预览。
|
||||
###上传下载
|
||||
采用全新上传控件,跟安全,更好的体验。
|
||||
拖拽支持文件夹,多个文件。上传自动过滤不允许的文件类型
|
||||
拖拽上传 和上统一优化,修复webuploader的文件判断;火狐拖拽上传,ie9+拖拽上传。
|
||||
上传时自动过滤不合格的文件,上传失败错误返回。
|
||||
###文件编辑
|
||||
编辑器支持多光标
|
||||
支持几乎所有编程语言的代码高亮
|
||||
支持代码自动补全(基于文档、或自定义的代码快照)
|
||||
快速预览功能
|
||||
优化文件保存完美解决。编码自动识别转换。(字符串转义问题。1&#'[{'"+~%25\\\\ ////)
|
||||
文件编辑,添加收藏夹
|
||||
优化音乐播放器,添加音乐后自动播放新添加的第一首;解决之前添加列表后暂停问题。
|
||||
优化任务栏,多标签;最小化flash问题(left+10000 visiable)
|
||||
ctrl,shift 多选时拖拽优化(按住这两个键时,不能拖动;拖动加入延迟200ms)
|
||||
编辑器在没打开文件的情况下工具栏不可用问题。
|
||||
搜索、替换;vim模式
|
||||
……
|
||||
###登陆退出
|
||||
登陆优化 ok【页面&验证码&记住密码】
|
||||
三次错误需要输入验证码,保证系统的安全性
|
||||
优化自动登录安全性,客户端保存cookie自动登录信息。【tooken加入本地ip】
|
||||
|
||||
###系统优化
|
||||
解决较慢操作,阻塞其他操作问题。(同一个用户session会加锁,入口处做释放)
|
||||
前后端代码基本全部重构,前端采用模块化方法sea.js|require.js 模块化。
|
||||
凡是有模板调用的(display——页面部分php解析。并将配置注入到页面js变量,便于js使用)
|
||||
加入模板机制;通用模块采用懒加载模式;使用artTemplate 对模板绑定数据。
|
||||
kv结构存储
|
||||
路由权限控制
|
||||
后端统一json输出。
|
||||
|
||||
|
||||
ver1.21 `2013/11/6`
|
||||
=====================
|
||||
##fix bug:
|
||||
* 修复文件下载bug
|
||||
* 修复编辑器自动补全问题,<aa bb /> ——> <aa bb></a>
|
||||
* 兼容部分服务器问题。
|
||||
|
||||
ver1.2 `2013/10/16`
|
||||
=====================
|
||||
##fix bug:
|
||||
* 设置,外部通用调用方式
|
||||
* 打包中文乱码问题。
|
||||
* simple,default主题,navbar 下拉菜单右边位置问题。
|
||||
* 文件管理:有滚动条时,上下超过可视区域框选问题修复,统一和win操作一致。
|
||||
* 文件大小写不敏感设置,扩展名获取bug
|
||||
* 目录读取权限判断,解决“系统错误”相关问题。
|
||||
##update:
|
||||
* 地址栏宽度自适应优化,支持浏览器窗口调整
|
||||
* 增加远程下载功能;上传功能优化,
|
||||
* 整体样式风格优化,
|
||||
* 右键菜单优化(可持续粘贴,剪切后粘贴清空剪贴板)。
|
||||
* 新建文件、文件重命名高度自适应优化
|
||||
* 关闭调试状态错误信息
|
||||
* 图片播放幻灯片优化,支持浏览器窗口调整,解决事件绑定bug,添加图片倒影;添加关闭按钮,关闭动画等功能
|
||||
* 优化桌面,弹出层层级问题;任务栏为最上层
|
||||
* 优化多标签,没有标签时不显示标签容器,放至层级覆盖
|
||||
* 地址栏超出宽度,自动隐藏最左边内容
|
||||
* 右键菜单状态同步,排序方式初始化当前值,设置后标记当前值。
|
||||
* 优化编辑器:拖动内容&文件到编辑区,内容处理。
|
||||
* 拖拽上传,信息框自动隐出后关闭
|
||||
* setting,editor,player最小化时,再次调用则显示出弹出层
|
||||
* 优化影音播放器,皮肤及相关配置信息存储于js中,不用之前的服务器请求方式,修改皮肤后可以直接更新到界面上。
|
||||
|
||||
|
||||
ver1.01 `2013/9/10`
|
||||
=====================
|
||||
##fix bug:
|
||||
* 添加到收藏
|
||||
* simple,default主题,navbar 下拉菜单右边位置问题。
|
||||
##update:
|
||||
* 添加到收藏夹,修改收藏夹,更新文件管理收藏夹部分。
|
||||
* 修改主题,同时修改编辑器主题。【编辑区,文件管理,桌面】
|
||||
* 优化setting部分代码,整合为一个整体。
|
||||
* 优化debug,增加less编译,导出功能优化,先编译后复制再操作
|
||||
|
||||
|
||||
ver1.0 `2013.9.1`
|
||||
=====================
|
||||
##update:
|
||||
* 代码模块化优化,静态文件分离,可以分开部署
|
||||
* 编辑器单独逻辑提取,完整融合到文件管理,树目录融合文件管理,懒加载语法高亮
|
||||
* 多标签实现,弹层对话框多标签支持,桌面任务栏实现;编辑器多标签支持
|
||||
* 弹层功能优化,实现最大最小化,最小化关联多标签任务栏管理
|
||||
##fix bug:
|
||||
* linux 下浏览器打开文件和文件夹,中文问题
|
||||
* 重命名&新建&上传 刷新列表使用动画,当前选中失效问题,不使用动画加载方式。
|
||||
* html5拖拽上传优化
|
||||
|
||||
|
||||
ver0.8 `2013.6.15`
|
||||
=====================
|
||||
##update:
|
||||
* 整体优化,实现全部操作ajax本地化 ,进一步提升体验
|
||||
* 浏览器强刷新,保持之前最后所在路径
|
||||
* 重命名,新建,粘贴操作后添加选中状态
|
||||
* 代码主题列表优化,重新设计,提高可配置性
|
||||
* 优化代码,添加getTplList模版,简化关联配置获取
|
||||
* 增加设置功能,ajax刷新设置。缩略图片增加tips预览(被注释frame/setting.php)
|
||||
* 增加重命名只选择名称部分功能
|
||||
* 增加iframe js api互操作ie支持。四大浏览器内核皆支持。
|
||||
* 文件夹打开,采用ajax实现。包括头部地址栏,父级目录,左边树目录以及收藏夹
|
||||
* 历史记录完美实现,前进后退按钮实时变化状态。
|
||||
* 快捷键backspace实现后退(left header main 分别加入函数,屏蔽默认history(-1)操作)
|
||||
##fix bug:
|
||||
* 完善修改windows以及linux获取文件列表,中文路径属性获取失败问题。
|
||||
* 复制,剪切。剪贴板内容覆盖判空处理
|
||||
* 修复一些地方ajax线程同步问题,重命名后选中失效问题解决
|
||||
* 修复返回上层目录,根目录检测
|
||||
* 修复linux下 音视频播放,中文路径问题
|
||||
* 修复文件右键菜单位置出错问题
|
||||
* 修复ie下frame js相互通信问题
|
||||
* ajax更新文件列表下,各种bug修复。进一步提升操作友好性
|
||||
* 修复当前目录改变的情况下,播放器消失的问题。现在能使播放器始终保留
|
|
@ -1,26 +0,0 @@
|
|||
{
|
||||
"eqeqeq": true,
|
||||
"forin": false,
|
||||
"latedef": false,
|
||||
"newcap": true,
|
||||
"quotmark": false,
|
||||
"undef": false,
|
||||
"unused": false,
|
||||
"trailing": true,
|
||||
"lastsemic": true,
|
||||
"asi": false,
|
||||
"boss": true,
|
||||
"expr": true,
|
||||
"strict": false,
|
||||
"es5": true,
|
||||
"funcscope": true,
|
||||
"loopfunc": true,
|
||||
"multistr": true,
|
||||
"proto": false,
|
||||
"smarttabs": true,
|
||||
"shadow": false,
|
||||
"sub": true,
|
||||
"passfail": false,
|
||||
"node": true,
|
||||
"white": false
|
||||
}
|
|
@ -1,4 +0,0 @@
|
|||
node_modules
|
||||
npm-debug.log
|
||||
*.iml
|
||||
tmp
|
|
@ -1,70 +0,0 @@
|
|||
/*
|
||||
* grunt-cmd-concat
|
||||
* https://github.com/spmjs/grunt-cmd-concat
|
||||
*
|
||||
* Copyright (c) 2013 Hsiaoming Yang
|
||||
* Licensed under the MIT license.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports = function(grunt) {
|
||||
|
||||
// Project configuration.
|
||||
grunt.initConfig({
|
||||
jshint: {
|
||||
all: [
|
||||
'Gruntfile.js',
|
||||
'tasks/**/*.js',
|
||||
'<%= nodeunit.tests %>',
|
||||
],
|
||||
options: {
|
||||
jshintrc: '.jshintrc',
|
||||
},
|
||||
},
|
||||
|
||||
// Before generating any new files, remove any previously-created files.
|
||||
clean: {
|
||||
tests: ['tmp'],
|
||||
},
|
||||
|
||||
concat: {
|
||||
dist: {
|
||||
options: {
|
||||
paths: ['test/sea-modules'],
|
||||
css2js: function(code, id) {
|
||||
return code + id;
|
||||
},
|
||||
relative: true
|
||||
},
|
||||
files: {
|
||||
'tmp/a.js': ['test/fixtures/a.js', 'test/fixtures/b.js'],
|
||||
'tmp/foo.js': ['test/fixtures/foo.js'],
|
||||
'tmp/foo.css': ['test/fixtures/foo.css'],
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
// Unit tests.
|
||||
nodeunit: {
|
||||
tests: ['test/*.test.js'],
|
||||
},
|
||||
|
||||
});
|
||||
|
||||
// Actually load this plugin's task(s).
|
||||
grunt.loadTasks('tasks');
|
||||
|
||||
// These plugins provide necessary tasks.
|
||||
grunt.loadNpmTasks('grunt-contrib-jshint');
|
||||
grunt.loadNpmTasks('grunt-contrib-clean');
|
||||
grunt.loadNpmTasks('grunt-contrib-nodeunit');
|
||||
|
||||
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
|
||||
// plugin's task(s), then test the result.
|
||||
grunt.registerTask('test', ['clean', 'concat', 'nodeunit']);
|
||||
|
||||
// By default, lint and run all tests.
|
||||
grunt.registerTask('default', ['jshint', 'test']);
|
||||
|
||||
};
|
|
@ -1,22 +0,0 @@
|
|||
Copyright (c) 2013 Hsiaoming Yang
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
|
@ -1,160 +0,0 @@
|
|||
# grunt-cmd-concat
|
||||
|
||||
> Concatenate cmd files.
|
||||
|
||||
## Getting Started
|
||||
This plugin requires Grunt `~0.4.0`
|
||||
|
||||
If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:
|
||||
|
||||
```shell
|
||||
npm install grunt-cmd-concat --save-dev
|
||||
```
|
||||
|
||||
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
|
||||
|
||||
```js
|
||||
grunt.loadNpmTasks('grunt-cmd-concat');
|
||||
```
|
||||
|
||||
## The "concat" task
|
||||
|
||||
### Overview
|
||||
In your project's Gruntfile, add a section named `concat` to the data object passed into `grunt.initConfig()`.
|
||||
|
||||
```js
|
||||
grunt.initConfig({
|
||||
concat: {
|
||||
options: {
|
||||
// Task-specific options go here.
|
||||
},
|
||||
your_target: {
|
||||
// Target-specific file lists and/or options go here.
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
#### options.paths
|
||||
|
||||
Type: `Array`
|
||||
Default value: `['sea-modules']`
|
||||
|
||||
Where are the modules in the sea.
|
||||
|
||||
|
||||
#### options.include
|
||||
|
||||
Type: `String`
|
||||
Default value: `'self'`
|
||||
Optional values:
|
||||
|
||||
- self
|
||||
- relative
|
||||
- all
|
||||
|
||||
How should it include its dependencies.
|
||||
|
||||
#### options.separator
|
||||
|
||||
Type: `String`
|
||||
Default value: `', '`
|
||||
|
||||
A string value that is used to do something with whatever.
|
||||
|
||||
#### options.banner
|
||||
|
||||
Type: `String`
|
||||
|
||||
The banner of the concated files.
|
||||
|
||||
#### options.relative
|
||||
|
||||
Type: `Boolean`
|
||||
Default value: `true`
|
||||
|
||||
Include all relative dependencies.
|
||||
|
||||
#### options.uglify
|
||||
|
||||
Type: `Object`
|
||||
|
||||
Uglify prettifier, you really don't have to change this value.
|
||||
|
||||
#### options.processors
|
||||
|
||||
Type: `Object`
|
||||
|
||||
Processors are functions to find the related files to concat.
|
||||
|
||||
|
||||
### Usage Examples
|
||||
|
||||
#### Simple Concat
|
||||
|
||||
This is the same as `grunt-contrib-concat`.
|
||||
|
||||
```js
|
||||
grunt.initConfig({
|
||||
concat: {
|
||||
foo: {
|
||||
files: {
|
||||
'dist/a.js': ['src/a.js', 'src/b.js'],
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
#### Relative Concat
|
||||
|
||||
This will include all relative dependencies.
|
||||
|
||||
**You should transport your modules first**, make sure your modules contain id and dependencies.
|
||||
|
||||
Get [transport task](https://github.com/spmjs/grunt-cmd-transport).
|
||||
|
||||
```js
|
||||
grunt.initConfig({
|
||||
concat: {
|
||||
foo: {
|
||||
options: {
|
||||
include: 'relative'
|
||||
},
|
||||
files: {
|
||||
'dist/a.js': ['src/a.js', 'src/b.js'],
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The `a.js` is something like:
|
||||
|
||||
```js
|
||||
define('a', ['./c'], ...)
|
||||
```
|
||||
|
||||
And the result should be the concat of `a.js`, `c.js` and `b.js`.
|
||||
|
||||
## Contributing
|
||||
|
||||
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).
|
||||
|
||||
## Release History
|
||||
|
||||
**April 11th, 2013** `0.2.0`
|
||||
|
||||
- Remove options.relative
|
||||
- Add options.include
|
||||
|
||||
**April 10th, 2013** `0.1.1`
|
||||
|
||||
- Update `cmd-util`
|
||||
- Bugfix
|
||||
|
||||
**April 1st, 2013** `0.1.0`
|
||||
|
||||
First version.
|
|
@ -1,55 +0,0 @@
|
|||
/*
|
||||
* grunt-cmd-concat
|
||||
* https://github.com/spmjs/grunt-cmd-concat
|
||||
*
|
||||
* Copyright (c) 2013 Hsiaoming Yang
|
||||
* Licensed under the MIT license.
|
||||
*/
|
||||
|
||||
module.exports = function(grunt) {
|
||||
|
||||
// Project configuration.
|
||||
grunt.initConfig({
|
||||
|
||||
concat: {
|
||||
self: {
|
||||
files: {
|
||||
'tmp/self.js': ['demo/self.js', 'demo/relative.js']
|
||||
}
|
||||
},
|
||||
|
||||
relative: {
|
||||
options: {
|
||||
include: 'relative'
|
||||
},
|
||||
files: {
|
||||
// it will auto concat demo/self.js
|
||||
'tmp/relative.js': ['demo/relative.js']
|
||||
}
|
||||
},
|
||||
|
||||
all: {
|
||||
options: {
|
||||
include: 'all',
|
||||
// the modules path
|
||||
paths: ['assets']
|
||||
},
|
||||
files: {
|
||||
// it will include all dependencies
|
||||
// demo/all.js demo/relative.js demo/self.js assets/foo.js
|
||||
'tmp/all.js': ['demo/all.js']
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// Actually load this plugin's task(s).
|
||||
grunt.loadTasks('../tasks');
|
||||
// for real project:
|
||||
// grunt.loadNpmTasks('grunt-cmd-concat')
|
||||
|
||||
// By default, lint and run all tests.
|
||||
grunt.registerTask('default', ['concat']);
|
||||
|
||||
};
|
|
@ -1,3 +0,0 @@
|
|||
define('foo', [], function() {
|
||||
return 'foo'
|
||||
});
|
|
@ -1,4 +0,0 @@
|
|||
define('all', ['./self', 'foo'], function(require) {
|
||||
require('./self')
|
||||
require('foo')
|
||||
});
|
|
@ -1,3 +0,0 @@
|
|||
define('relative', ['./self'], function(require) {
|
||||
require('./self')
|
||||
});
|
|
@ -1,3 +0,0 @@
|
|||
define('self', [], function() {
|
||||
return 'self'
|
||||
});
|
|
@ -1,25 +0,0 @@
|
|||
{
|
||||
"eqeqeq": true,
|
||||
"forin": false,
|
||||
"latedef": false,
|
||||
"newcap": true,
|
||||
"quotmark": false,
|
||||
"undef": false,
|
||||
"unused": false,
|
||||
"trailing": true,
|
||||
"lastsemic": true,
|
||||
"asi": false,
|
||||
"boss": true,
|
||||
"expr": true,
|
||||
"strict": false,
|
||||
"es5": true,
|
||||
"funcscope": true,
|
||||
"loopfunc": true,
|
||||
"multistr": true,
|
||||
"proto": false,
|
||||
"smarttabs": true,
|
||||
"shadow": false,
|
||||
"sub": true,
|
||||
"passfail": false,
|
||||
"white": false
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
*.iml
|
||||
.idea/
|
||||
.ipr
|
||||
.iws
|
||||
*~
|
||||
~*
|
||||
*.diff
|
||||
*.patch
|
||||
*.bak
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.project
|
||||
.*proj
|
||||
.svn/
|
||||
*.swp
|
||||
*.swo
|
||||
*.log
|
||||
node_modules/
|
||||
dist/
|
||||
.buildpath
|
||||
.settings
|
||||
.yml
|
||||
_site
|
|
@ -1,3 +0,0 @@
|
|||
language: node_js
|
||||
node_js:
|
||||
- 0.8
|
|
@ -1,57 +0,0 @@
|
|||
# Contributing
|
||||
|
||||
First, please do contribute!
|
||||
|
||||
English and Chinese issues are acceptable, talk in your favorite language.
|
||||
|
||||
Pull request and git commit message must be in English, if your commit message is in other language, it will be rejected.
|
||||
|
||||
|
||||
## Issues
|
||||
|
||||
When you submit an issue, please format your content, a readable content helps a lot. You should have a little knowledge on [Markdown](http://github.github.com/github-flavored-markdown/).
|
||||
|
||||
Code talks. If you can't make yourself understood, show us the code.
|
||||
|
||||
|
||||
## Codebase
|
||||
|
||||
The codebase of `cmd-util` is highly tested and linted, as a way to guarantee functionality and keep all code written in a particular style for readability.
|
||||
|
||||
You should follow the code style, and if you add any code, please add test cases for them.
|
||||
|
||||
Here is a little tips to make things simple:
|
||||
|
||||
- when you cloned this repo, run `make`, it will prepare everything for you
|
||||
- check the code style with `make lint`
|
||||
- check the test case with `make test`
|
||||
|
||||
If you are on Windows, you should have a look at the `Makefile` and find out what you should do. If you are familiar with Windows, please add a `make.bat` for me.
|
||||
|
||||
|
||||
## Git Help
|
||||
|
||||
Something you should know about git.
|
||||
|
||||
- don't add any code on the master branch, create a new one
|
||||
- don't add too many code in one pull request
|
||||
- all featured branches should be based on the master branch
|
||||
|
||||
Take an example, if you want to add feature A and feature B, you should have two branches:
|
||||
|
||||
```
|
||||
$ git branch feature-A
|
||||
$ git checkout feature-A
|
||||
```
|
||||
|
||||
Now code on feature-A branch, and when you finish feature A:
|
||||
|
||||
```
|
||||
$ git checkout master
|
||||
$ git branch feature-B
|
||||
$ git checkout feature-B
|
||||
```
|
||||
|
||||
All branches must be based on the master branch. If your feature-B needs feature-A, you should send feature-A first, and wait for its merging. We may reject feature-A, and you should stop feature-B.
|
||||
|
||||
We use a none fast forward merging strategy, please don't `git rebase`.
|
|
@ -1,36 +0,0 @@
|
|||
all:
|
||||
@npm install -d
|
||||
@cp scripts/githooks/* .git/hooks/
|
||||
@chmod -R +x .git/hooks/
|
||||
|
||||
|
||||
specs := $(shell find ./tests -name '*.test.js' ! -path "*node_modules/*")
|
||||
reporter = spec
|
||||
test:
|
||||
@node_modules/.bin/mocha --reporter ${reporter} ${specs}
|
||||
|
||||
jsfiles := $(shell find ./ -name '*.js' ! -path "*node_modules/*" ! -path "*scripts/*");
|
||||
lint:
|
||||
@node_modules/.bin/jshint ${jsfiles}
|
||||
|
||||
out = _site/coverage.html
|
||||
coverage:
|
||||
@rm -rf lib-cov
|
||||
@jscoverage lib lib-cov
|
||||
@CMD_COVERAGE=1 $(MAKE) test reporter=html-cov > ${out}
|
||||
@rm -rd lib-cov
|
||||
@echo
|
||||
@echo "Built Report to ${out}"
|
||||
@echo
|
||||
|
||||
clean:
|
||||
@rm -fr _site
|
||||
|
||||
theme = ~/.spm/themes/one
|
||||
documentation:
|
||||
@nico build --theme ${theme} -C scripts/nico.json
|
||||
|
||||
server:
|
||||
@nico server --theme ${theme} -C scripts/nico.json
|
||||
|
||||
.PHONY: all build test lint coverage
|
|
@ -1,69 +0,0 @@
|
|||
# cmd-util [![Build Status](https://travis-ci.org/spmjs/cmd-util.png)](https://travis-ci.org/spmjs/cmd-util)
|
||||
|
||||
Utilities for common module definition.
|
||||
|
||||
---------------------------
|
||||
|
||||
This package is designed for developers, if you are a user, don't read this.
|
||||
|
||||
**100% test coverage**
|
||||
|
||||
## Implements
|
||||
|
||||
- **ast**: parse cmd javascript code, do whatever you want.
|
||||
- **css**: css parser
|
||||
- **iduri**: solutions for id and uri.
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
$ npm install cmd-util
|
||||
```
|
||||
|
||||
Get the unstable version with:
|
||||
|
||||
```
|
||||
$ npm install cmd-util@ninja
|
||||
```
|
||||
|
||||
## Contribute
|
||||
|
||||
Yes, please do contribute. But before this, you should read our [Contributing Guide](https://github.com/spmjs/cmd-util/blob/master/CONTRIBUTING.md).
|
||||
|
||||
## Changelog
|
||||
|
||||
**April 8th, 2013** `0.3.5`
|
||||
|
||||
1. Fix parse dependency of `require('foo')('bar')`
|
||||
|
||||
**Mar 29, 2013** `0.3.4`
|
||||
|
||||
1. Only parse `require`, don't parse `require.async`
|
||||
|
||||
**Mar 19, 2013** `0.3.3`
|
||||
|
||||
1. Enhancement of ast. Delete a dependency by `return null`
|
||||
|
||||
**Mar 16, 2013** `0.3.2`
|
||||
|
||||
1. add `iduri.validateFormat`
|
||||
|
||||
**Mar 14, 2013** `0.3.1`
|
||||
|
||||
1. make `css.walk` the right way
|
||||
2. add `css.strigify`
|
||||
|
||||
**Mar 14, 2013** `0.3.0`
|
||||
|
||||
1. add css parser
|
||||
|
||||
**Mar 2, 2013** `0.2.0`
|
||||
|
||||
1. ast.modify return ast instead of string
|
||||
2. iduri.resolve only resolve cmd uri
|
||||
3. rewrite ast parser
|
||||
|
||||
**Feb 1, 2013** `0.1.0`
|
||||
|
||||
This first version.
|
|
@ -1,140 +0,0 @@
|
|||
# ast
|
||||
|
||||
- pubdate: 2013-01-29
|
||||
|
||||
The AST of javascript.
|
||||
|
||||
-----
|
||||
|
||||
```js
|
||||
var ast = require('cmd-util').ast
|
||||
```
|
||||
|
||||
## ast.parseFirst(code)
|
||||
|
||||
Get information of the first `define`:
|
||||
|
||||
```js
|
||||
define('id', ['a'], function(require) {
|
||||
var $ = require('jquery')
|
||||
});
|
||||
```
|
||||
|
||||
When `ast.parse(code)` this code block, it will return:
|
||||
|
||||
```js
|
||||
{id: 'id', dependencies: ['a'], factory: factoryNode}
|
||||
```
|
||||
|
||||
If the `define` only has a factory:
|
||||
|
||||
```js
|
||||
define(function(require) {
|
||||
var $ = require('jquery')
|
||||
});
|
||||
```
|
||||
|
||||
The result should be:
|
||||
|
||||
```js
|
||||
{id: null, dependencies: ['jquery'], factory: factoryNode}
|
||||
```
|
||||
|
||||
|
||||
## ast.parse(code)
|
||||
|
||||
Information or meta data in every `define`:
|
||||
|
||||
```js
|
||||
define('id', ['a'], {})
|
||||
define(function(require) {
|
||||
var $ = require('jquery')
|
||||
});
|
||||
```
|
||||
|
||||
The result of `ast.parse(code)`:
|
||||
|
||||
```js
|
||||
[
|
||||
{id: 'id', dependencies: ['a'], factory: factoryNode},
|
||||
{id: null, dependencies: ['jquery'], factory: factoryNode}
|
||||
]
|
||||
```
|
||||
|
||||
## ast.modify(code, {id: fn, dependencies: fn, require: fn})
|
||||
|
||||
Modify meta data in the `define`, it returns ast, get the string with:
|
||||
|
||||
```js
|
||||
var m = ast.modify(code, ...)
|
||||
console.log(m.print_to_string())
|
||||
```
|
||||
|
||||
Some examples of `ast.modify`:
|
||||
|
||||
```js
|
||||
// define({})
|
||||
ast.modify(code, {id: 'id', dependencies: ['a']})
|
||||
|
||||
// => define('id', ['a'], {})
|
||||
```
|
||||
|
||||
```js
|
||||
// define('id', ['a'], {})
|
||||
ast.modify(code, {id: function(v) { return v + '-debug'}})
|
||||
|
||||
// => define('id-debug', ['a'], {})
|
||||
```
|
||||
|
||||
```js
|
||||
// define('id', [], function(require) { var $ = require('jquery') })
|
||||
ast.modify(code, {require: function(v) {
|
||||
if (v === 'jquery') return '$';
|
||||
});
|
||||
|
||||
// => define('id', [], function(require) { var $ = require('$') })
|
||||
```
|
||||
|
||||
```js
|
||||
// define('id', [], function(require) { var $ = require('jquery') })
|
||||
ast.modify(code, {require: {'jquery': '$'}});
|
||||
|
||||
// => define('id', [], function(require) { var $ = require('$') })
|
||||
```
|
||||
|
||||
You can delete a dependencies by `return null`.
|
||||
|
||||
```js
|
||||
// define('id', ['jquery', 'a', 'b'], {})
|
||||
ast.modify(code, {dependencies: function(v) {
|
||||
if (v === 'jquery') return null;
|
||||
return v;
|
||||
});
|
||||
// => define('id', ['a', 'b'], {})
|
||||
```
|
||||
|
||||
## ast.modify(code, fn)
|
||||
|
||||
Modify every meta data with the function:
|
||||
|
||||
```js
|
||||
define('id', ['a'], function(require) {
|
||||
var $ = require('jquery')
|
||||
});
|
||||
```
|
||||
|
||||
Modify the code with:
|
||||
|
||||
```js
|
||||
ast.modify(code, function(v) {
|
||||
return v + '-debug'
|
||||
})
|
||||
```
|
||||
|
||||
The result should be:
|
||||
|
||||
```js
|
||||
define('id-debug', ['a-debug'], function(require) {
|
||||
var $ = require('jquery-debug');
|
||||
});
|
||||
```
|
|
@ -1,71 +0,0 @@
|
|||
# css
|
||||
|
||||
- pubdate: 2013-03-14
|
||||
|
||||
The css parser
|
||||
|
||||
-----
|
||||
|
||||
```js
|
||||
var css = require('cmd-util').css
|
||||
```
|
||||
|
||||
|
||||
## css.parse(code)
|
||||
|
||||
When a css data is parsed, it will return a data structure like:
|
||||
|
||||
```js
|
||||
[{
|
||||
type: 'block',
|
||||
id: 'alice/button/1.0.0/button.css',
|
||||
code: [
|
||||
{
|
||||
type: 'import',
|
||||
id: 'base'
|
||||
},
|
||||
{
|
||||
type: 'string',
|
||||
code: '...'
|
||||
}
|
||||
{
|
||||
type: 'import',
|
||||
id: 'alice/class/1.0.0/class.css'
|
||||
},
|
||||
{
|
||||
type: 'string',
|
||||
code: '...',
|
||||
},
|
||||
{
|
||||
type: 'block',
|
||||
id: 'alice/button/1.0.1/button.css',
|
||||
code: [
|
||||
{
|
||||
type: 'string',
|
||||
code: '....'
|
||||
}
|
||||
]
|
||||
}
|
||||
...
|
||||
]
|
||||
}]
|
||||
```
|
||||
|
||||
## css.walk(code, filter)
|
||||
|
||||
Walk through the code:
|
||||
|
||||
```js
|
||||
var ids = [];
|
||||
css.walk(code, function(node) {
|
||||
if (node.id) {
|
||||
ids.push(node.id);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
You can stop the walk by `return false`.
|
||||
|
||||
## css.stringify(code, filter)
|
||||
|
||||
Stringify the parsed code.
|
|
@ -1,110 +0,0 @@
|
|||
# iduri
|
||||
|
||||
- pubdate: 2013-03-16
|
||||
|
||||
-----
|
||||
|
||||
```js
|
||||
var iduri = require('cmd-util').iduri
|
||||
```
|
||||
|
||||
## iduri.resovle(uri)
|
||||
|
||||
Resolve uri to an object. Demo talks:
|
||||
|
||||
```js
|
||||
// iduri.resovle('arale/base')
|
||||
// iduri.resovle('arale.base')
|
||||
{
|
||||
family: 'arale',
|
||||
name: 'base',
|
||||
version: '',
|
||||
}
|
||||
```
|
||||
|
||||
Supported formats:
|
||||
|
||||
- family/name@version
|
||||
- family/name#version
|
||||
- family.name@version
|
||||
- family/name#version
|
||||
|
||||
```js
|
||||
// iduri.resovle('seajs')
|
||||
{
|
||||
family: 'seajs',
|
||||
name: 'seajs',
|
||||
version: '',
|
||||
}
|
||||
```
|
||||
|
||||
If family is the same as name, the supported formats:
|
||||
|
||||
- name@version
|
||||
- name#version
|
||||
|
||||
|
||||
## iduri.normalize(uri)
|
||||
|
||||
Normalize uri and make sure the uri to be pretty.
|
||||
|
||||
```js
|
||||
iduri.normalize('a//b/../c')
|
||||
|
||||
// => a/c
|
||||
```
|
||||
|
||||
## iduri.relative(base, uri)
|
||||
|
||||
|
||||
## iduri.absolute(base, uri)
|
||||
|
||||
Generate the absolute id:
|
||||
|
||||
```js
|
||||
iduri.absolute('arale/widget/1.0.0/daparser', './base')
|
||||
|
||||
// => arale/base/1.0.0/base
|
||||
```
|
||||
|
||||
## iduri.join(base, uri)
|
||||
|
||||
The same as `path.join`.
|
||||
|
||||
## iduri.dirname(uri)
|
||||
|
||||
The same as `path.dirname`.
|
||||
|
||||
## iduri.basename(uri)
|
||||
|
||||
The same as `path.basename`.
|
||||
|
||||
## iduri.extname(uri)
|
||||
|
||||
The same as `path.extname`.
|
||||
|
||||
However, if no extname is found, it will return `.js`.
|
||||
|
||||
## iduri.appendext(uri)
|
||||
|
||||
If uri has no extname, append `.js` to it.
|
||||
|
||||
## iduri.parseAlias(pkg, name)
|
||||
|
||||
Find `name` in `pkg.spm.alias`.
|
||||
|
||||
## iduri.isAlias(pkg, name)
|
||||
|
||||
If the name is an alias.
|
||||
|
||||
## iduri.idFromPackage(pkg, filename, format)
|
||||
|
||||
Generate id from package with the format. Default format is:
|
||||
|
||||
```
|
||||
'{{ family }}/{{ name }}/{{ version }}/{{ filename }}'
|
||||
```
|
||||
|
||||
## iduri.validateFormat(format)
|
||||
|
||||
Detect if the format is the default format.
|
|
@ -1,3 +0,0 @@
|
|||
exports.ast = require('./lib/ast');
|
||||
exports.css = require('./lib/css');
|
||||
exports.iduri = require('./lib/iduri');
|
|
@ -1,312 +0,0 @@
|
|||
/*
|
||||
* spm.sdk.ast
|
||||
* https://spmjs.org
|
||||
*
|
||||
* Hsiaoming Yang <lepture@me.com>
|
||||
*/
|
||||
|
||||
var util = require('util');
|
||||
var UglifyJS = require('uglify-js');
|
||||
|
||||
|
||||
// UglifyJS ast.
|
||||
function getAst(ast, options) {
|
||||
if (isString(ast)) {
|
||||
return UglifyJS.parse(ast, options || {});
|
||||
}
|
||||
return ast;
|
||||
}
|
||||
exports.getAst = getAst;
|
||||
|
||||
|
||||
// A standard cmd module:
|
||||
//
|
||||
// define('id', ['deps'], fn)
|
||||
//
|
||||
// Return everything in define:
|
||||
//
|
||||
// {id: 'id', dependencies: ['deps'], factory: ast of fn}
|
||||
function parse(ast) {
|
||||
ast = getAst(ast);
|
||||
var meta = [];
|
||||
|
||||
var walker = new UglifyJS.TreeWalker(function(node, descend) {
|
||||
var id, factory, dependencies = [];
|
||||
// don't collect dependencies in the define in define
|
||||
if (node instanceof UglifyJS.AST_Call && node.start.value === 'define') {
|
||||
var define = getDefine(node);
|
||||
if (define) {
|
||||
meta.push(define);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
ast.walk(walker);
|
||||
return meta;
|
||||
}
|
||||
exports.parse = parse;
|
||||
|
||||
exports.parseFirst = function(ast) {
|
||||
return parse(ast)[0];
|
||||
};
|
||||
|
||||
|
||||
// Replace everything in `define` and `require`.
|
||||
//
|
||||
// define('id', ['a'], function(require) {
|
||||
// var $ = require('jquery')
|
||||
// })
|
||||
//
|
||||
// Replace the code with:
|
||||
//
|
||||
// replaceAll(code, function(value) {
|
||||
// return value + '-debug';
|
||||
// })
|
||||
//
|
||||
// The result will be:
|
||||
//
|
||||
// define('id-debug', ['a-debug'], function(require) {
|
||||
// var $ = require('jquery-debug')
|
||||
// })
|
||||
function modify(ast, options) {
|
||||
ast = getAst(ast);
|
||||
|
||||
var idfn, depfn, requirefn;
|
||||
if (isFunction(options)) {
|
||||
idfn = depfn = requirefn = options;
|
||||
} else {
|
||||
idfn = options.id;
|
||||
depfn = options.dependencies;
|
||||
requirefn = options.require;
|
||||
}
|
||||
|
||||
if (isObject(depfn)) {
|
||||
var alias = depfn;
|
||||
depfn = function(value) {
|
||||
if (alias.hasOwnProperty(value)) {
|
||||
return alias[value];
|
||||
} else {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var trans = new UglifyJS.TreeTransformer(function(node, descend) {
|
||||
// modify define
|
||||
if ((idfn || depfn) && node instanceof UglifyJS.AST_Call && node.start.value === 'define' && node.args.length) {
|
||||
var args = [];
|
||||
var meta = getDefine(node);
|
||||
var deps = [];
|
||||
if (idfn && isFunction(idfn)) {
|
||||
meta.id = idfn(meta.id);
|
||||
} else if (idfn && isString(idfn)) {
|
||||
meta.id = idfn;
|
||||
}
|
||||
if (meta.id) {
|
||||
args.push(new UglifyJS.AST_String({
|
||||
value: meta.id
|
||||
}));
|
||||
}
|
||||
// modify dependencies
|
||||
if (meta.dependencyNode && !depfn) {
|
||||
args.push(meta.dependencyNode);
|
||||
} else if (depfn) {
|
||||
var elements = [];
|
||||
if (meta.dependencies.length && isFunction(depfn)) {
|
||||
meta.dependencies.forEach(function(d) {
|
||||
var value = depfn(d);
|
||||
if (value) {
|
||||
elements.push(
|
||||
new UglifyJS.AST_String({value: value})
|
||||
);
|
||||
}
|
||||
});
|
||||
} else if (isString(depfn)) {
|
||||
elements = [new UglifyJS.AST_String({value: depfn})];
|
||||
} else if (Array.isArray(depfn)) {
|
||||
elements = depfn.map(function(value) {
|
||||
return new UglifyJS.AST_String({
|
||||
value: value
|
||||
});
|
||||
});
|
||||
}
|
||||
if (meta.dependencyNode) {
|
||||
args.push(new UglifyJS.AST_Array({
|
||||
start: meta.dependencyNode.start,
|
||||
end: meta.dependencyNode.end,
|
||||
elements: elements
|
||||
}));
|
||||
} else {
|
||||
args.push(new UglifyJS.AST_Array({elements: elements}));
|
||||
}
|
||||
} else {
|
||||
args.push(new UglifyJS.AST_Array({elements: []}));
|
||||
}
|
||||
if (meta.factory) {
|
||||
args.push(meta.factory);
|
||||
}
|
||||
return new UglifyJS.AST_Call({
|
||||
start: node.start,
|
||||
end: node.end,
|
||||
expression: node.expression,
|
||||
args: args
|
||||
});
|
||||
}
|
||||
});
|
||||
ast = ast.transform(trans);
|
||||
|
||||
if (requirefn) {
|
||||
ast = replaceRequire(ast, requirefn);
|
||||
}
|
||||
return ast;
|
||||
}
|
||||
exports.modify = modify;
|
||||
|
||||
|
||||
function getDefine(node) {
|
||||
var id, factory, dependencyNode, dependencies = [];
|
||||
// don't collect dependencies in the define in define
|
||||
if (node instanceof UglifyJS.AST_Call && node.start.value === 'define') {
|
||||
if (!node.args || !node.args.length) return null;
|
||||
|
||||
if (node.args.length === 1) {
|
||||
factory = node.args[0];
|
||||
if (factory instanceof UglifyJS.AST_Function) {
|
||||
dependencies = getRequires(factory);
|
||||
}
|
||||
} else if (node.args.length === 2) {
|
||||
factory = node.args[1];
|
||||
var child = node.args[0];
|
||||
if (child instanceof UglifyJS.AST_Array) {
|
||||
// define([], function(){});
|
||||
dependencies = map(child.elements, function(el) {
|
||||
if (el instanceof UglifyJS.AST_String) {
|
||||
return el.getValue();
|
||||
}
|
||||
});
|
||||
dependencyNode = child;
|
||||
}
|
||||
if (child instanceof UglifyJS.AST_String) {
|
||||
// define('id', function() {});
|
||||
id = child.getValue();
|
||||
}
|
||||
} else {
|
||||
factory = node.args[2];
|
||||
var firstChild = node.args[0], secondChild = node.args[1];
|
||||
if (firstChild instanceof UglifyJS.AST_String) {
|
||||
id = firstChild.getValue();
|
||||
}
|
||||
if (secondChild instanceof UglifyJS.AST_Array) {
|
||||
dependencies = map(secondChild.elements, function(el) {
|
||||
if (el instanceof UglifyJS.AST_String) {
|
||||
return el.getValue();
|
||||
}
|
||||
});
|
||||
}
|
||||
dependencyNode = secondChild;
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: id, dependencies: dependencies, factory: factory,
|
||||
dependencyNode: dependencyNode
|
||||
};
|
||||
}
|
||||
|
||||
// A standard cmd module:
|
||||
//
|
||||
// define(function(require) {
|
||||
// var $ = require('jquery')
|
||||
// var _ = require('lodash')
|
||||
// })
|
||||
//
|
||||
// Return everything in `require`: ['jquery', 'lodash'].
|
||||
function getRequires(ast) {
|
||||
ast = getAst(ast);
|
||||
|
||||
var deps = [];
|
||||
|
||||
var walker = new UglifyJS.TreeWalker(function(node, descend) {
|
||||
if (node instanceof UglifyJS.AST_Call && node.start.value === 'require' && !node.expression.property) {
|
||||
var args = node.expression.args || node.args;
|
||||
if (args && args.length === 1) {
|
||||
var child = args[0];
|
||||
if (child instanceof UglifyJS.AST_String) {
|
||||
deps.push(child.getValue());
|
||||
}
|
||||
// TODO warning
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
ast.walk(walker);
|
||||
return deps;
|
||||
}
|
||||
|
||||
// Replace every string in `require`.
|
||||
//
|
||||
// define(function(require) {
|
||||
// var $ = require('jquery')
|
||||
// })
|
||||
//
|
||||
// Replace requires in this code:
|
||||
//
|
||||
// replaceRequire(code, function(value) {
|
||||
// if (value === 'jquery') return 'zepto';
|
||||
// return value;
|
||||
// })
|
||||
function replaceRequire(ast, fn) {
|
||||
ast = getAst(ast);
|
||||
|
||||
if (isObject(fn)) {
|
||||
var alias = fn;
|
||||
fn = function(value) {
|
||||
if (alias.hasOwnProperty(value)) {
|
||||
return alias[value];
|
||||
} else {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var trans = new UglifyJS.TreeTransformer(function(node, descend) {
|
||||
// modify require
|
||||
if (fn && node instanceof UglifyJS.AST_Call && node.start.value === 'require' && node.args.length === 1) {
|
||||
var child = node.args[0];
|
||||
if (child instanceof UglifyJS.AST_String) {
|
||||
var requiredNode = new UglifyJS.AST_String({
|
||||
start: child.start,
|
||||
end: child.end,
|
||||
value: fn(child.getValue())
|
||||
});
|
||||
return new UglifyJS.AST_Call({
|
||||
start: node.start,
|
||||
end: node.start,
|
||||
expression: node.expression,
|
||||
args: [requiredNode]
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
return ast.transform(trans);
|
||||
}
|
||||
|
||||
function isString(str) {
|
||||
return typeof str === 'string';
|
||||
}
|
||||
function isFunction(fn) {
|
||||
return typeof fn === 'function';
|
||||
}
|
||||
function isObject(obj) {
|
||||
return (typeof obj === 'object' && !Array.isArray(obj));
|
||||
}
|
||||
function map(obj, fn, context) {
|
||||
var results = [];
|
||||
if (obj === null) return results;
|
||||
if (obj.map === Array.prototype.map) return obj.map(fn, context);
|
||||
|
||||
for (var i = 0; i < obj.length; i++) {
|
||||
results[i] = fn.call(context, obj[i], i, obj);
|
||||
}
|
||||
return results;
|
||||
}
|
|
@ -1,223 +0,0 @@
|
|||
/*
|
||||
* css
|
||||
* https://github.com/spmjs/spm2/issues/4
|
||||
*
|
||||
* Hsiaoming Yang <lepture@me.com>
|
||||
*/
|
||||
|
||||
/*
|
||||
* parse code into a tree
|
||||
*/
|
||||
exports.parse = function(code) {
|
||||
var lines = code.split(/\r\n|\r|\n/);
|
||||
var isStarted = false;
|
||||
var id, line;
|
||||
|
||||
// clean blank lines
|
||||
while (!isStarted && lines.length) {
|
||||
line = lines[0];
|
||||
if (line.trim()) {
|
||||
isStarted = true;
|
||||
id = match(line, 'define');
|
||||
if (id) {
|
||||
lines = lines.slice(1);
|
||||
}
|
||||
} else {
|
||||
lines = lines.slice(1);
|
||||
}
|
||||
}
|
||||
var node = {};
|
||||
if (id) {
|
||||
node.id = id;
|
||||
}
|
||||
node.type = 'block';
|
||||
node.code = parseBlock(lines.join('\n'));
|
||||
return [node];
|
||||
};
|
||||
|
||||
function match(text, key) {
|
||||
// /*! key value */
|
||||
var re = new RegExp('^\\/\\*!\\s*' + key + '\\s+(.*?)\\s*\\*\\/$');
|
||||
var m = text.match(re);
|
||||
if (!m) return;
|
||||
return m[1];
|
||||
}
|
||||
|
||||
/*
|
||||
* recursive parse a block type code
|
||||
*/
|
||||
function parseBlock(code) {
|
||||
var lines = code.split(/\r\n|\r|\n/);
|
||||
var tree = [];
|
||||
|
||||
var stringNode = {
|
||||
type: 'string',
|
||||
code: ''
|
||||
};
|
||||
var blockNode = {};
|
||||
var blockDepth = 0;
|
||||
|
||||
|
||||
while (lines.length) {
|
||||
parseInBlock();
|
||||
}
|
||||
|
||||
function pushStringNode() {
|
||||
if (!stringNode.code) return;
|
||||
var text = stringNode.code.replace(/^\n+/, '');
|
||||
text = text.replace(/\n+$/, '');
|
||||
if (text) {
|
||||
stringNode.code = text;
|
||||
tree.push(stringNode);
|
||||
}
|
||||
stringNode = {
|
||||
type: 'string',
|
||||
code: ''
|
||||
};
|
||||
}
|
||||
|
||||
function parseLine() {
|
||||
if (blockDepth !== 0) return;
|
||||
|
||||
var text = lines.shift();
|
||||
var re = /^@import\s+(?:url\()?(\'|\")([^\)]+)\1\)?;?\s*$/;
|
||||
|
||||
var m = match(text, 'import');
|
||||
if (!m) {
|
||||
m = text.match(re);
|
||||
m = m ? m[2]: null;
|
||||
}
|
||||
if (m) {
|
||||
pushStringNode();
|
||||
tree.push({
|
||||
id: m,
|
||||
type: 'import'
|
||||
});
|
||||
return;
|
||||
} else {
|
||||
stringNode.code = [stringNode.code, text].join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
function parseInBlock() {
|
||||
var text = lines[0];
|
||||
var start = match(text, 'block');
|
||||
if (start) {
|
||||
lines = lines.slice(1);
|
||||
if (blockDepth === 0) {
|
||||
pushStringNode();
|
||||
blockNode.id = start;
|
||||
blockNode.type = 'block';
|
||||
blockNode.code = '';
|
||||
} else {
|
||||
blockNode.code = [blockNode.code, text].join('\n');
|
||||
}
|
||||
blockDepth++;
|
||||
return;
|
||||
}
|
||||
/*! endblock id */
|
||||
var re = /\/\*!\s*endblock(\s+[^\*]*)?\s*\*\/$/;
|
||||
var end = text.match(re);
|
||||
if (end) {
|
||||
blockDepth--;
|
||||
if (blockDepth < 0) {
|
||||
throw new Error('block indent error.');
|
||||
}
|
||||
|
||||
lines = lines.slice(1);
|
||||
if (blockDepth === 0) {
|
||||
blockNode.code = parseBlock(blockNode.code);
|
||||
tree.push(blockNode);
|
||||
// reset block node
|
||||
blockNode = {};
|
||||
} else {
|
||||
blockNode.code = [blockNode.code, text].join('\n');
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (blockDepth > 0) {
|
||||
lines = lines.slice(1);
|
||||
blockNode.code = [blockNode.code, text].join('\n');
|
||||
} else {
|
||||
parseLine();
|
||||
}
|
||||
}
|
||||
|
||||
if (blockDepth !== 0) {
|
||||
throw new Error('block not finished.');
|
||||
}
|
||||
|
||||
pushStringNode();
|
||||
return tree;
|
||||
}
|
||||
|
||||
/*
|
||||
* Walk through the code tree
|
||||
*/
|
||||
exports.walk = function(code, fn) {
|
||||
if (!Array.isArray(code)) {
|
||||
code = exports.parse(code);
|
||||
}
|
||||
|
||||
function walk(code) {
|
||||
// if fn return false, it will stop the walk
|
||||
if (Array.isArray(code)) {
|
||||
code.forEach(function(node) {
|
||||
if (fn(node) !== false && node.type === 'block' && Array.isArray(node.code)) {
|
||||
walk(node.code, node);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
walk(code);
|
||||
};
|
||||
|
||||
/*
|
||||
* print string of the parsed code
|
||||
*/
|
||||
exports.stringify = function(code, filter) {
|
||||
if (!Array.isArray(code)) {
|
||||
return code;
|
||||
}
|
||||
|
||||
function print(code) {
|
||||
var cursor = '';
|
||||
|
||||
code.forEach(function(node) {
|
||||
if (filter) {
|
||||
var ret = filter(node);
|
||||
if (ret === false) return;
|
||||
if (ret && ret.type) node = ret;
|
||||
}
|
||||
if (node.type === 'string') {
|
||||
cursor = [cursor, node.code].join('\n');
|
||||
return;
|
||||
}
|
||||
if (node.type === 'import') {
|
||||
cursor = [cursor, '/*! import ' + node.id + ' */'].join('\n');
|
||||
return;
|
||||
}
|
||||
if (node.type === 'block' && node.id) {
|
||||
cursor = [
|
||||
cursor,
|
||||
'',
|
||||
'/*! block ' + node.id + ' */',
|
||||
print(node.code),
|
||||
'/*! endblock ' + node.id + ' */',
|
||||
'',
|
||||
].join('\n');
|
||||
return;
|
||||
}
|
||||
if (node.type === 'block' && ! node.id) {
|
||||
cursor = print(node.code);
|
||||
return;
|
||||
}
|
||||
});
|
||||
cursor = cursor.replace(/^\n+/, '');
|
||||
cursor = cursor.replace(/\n+$/, '');
|
||||
cursor = cursor.replace(/\n{3,}/g, '\n\n');
|
||||
return cursor;
|
||||
}
|
||||
|
||||
return print(code);
|
||||
};
|
|
@ -1,193 +0,0 @@
|
|||
/*
|
||||
* iduri
|
||||
* https://spmjs.org
|
||||
*
|
||||
* Hsiaoming Yang <lepture@me.com>
|
||||
*/
|
||||
|
||||
var path = require('path');
|
||||
|
||||
// resolve uri to meta info
|
||||
exports.resolve = function(uri) {
|
||||
// family/name@version
|
||||
// family/name#version
|
||||
// family.name@version
|
||||
// family.name#version
|
||||
|
||||
var regex = /^([a-z][a-z0-9]*(?:\/|\.))?([a-zA-Z][a-zA-Z0-9\-]*)((?:@|#).*)?$/;
|
||||
var m = uri.match(regex);
|
||||
|
||||
var family = m[1] || '';
|
||||
family = family.replace(/\/|\.$/, '');
|
||||
var name = m[2] || '';
|
||||
var version = m[3] || '';
|
||||
version = version.replace(/^@|#/, '');
|
||||
if (!family) {
|
||||
if (/^[a-z][a-z0-9]*$/.test(name)) {
|
||||
family = name;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (!family && !name && !version) return null;
|
||||
return {family: family, name: name, version: version};
|
||||
};
|
||||
|
||||
|
||||
// normalize uri
|
||||
// make sure the uri to be pretty,
|
||||
// for example a//b/../c should be a/c.
|
||||
function normalize(uri) {
|
||||
uri = path.normalize(uri);
|
||||
uri = uri.replace(/\\/g, '/');
|
||||
var lastChar = uri.charAt(uri.length - 1);
|
||||
if (lastChar === '/') return uri;
|
||||
// if it ends with #, we should return the uri without #
|
||||
if (lastChar === '#') return uri.slice(0, -1);
|
||||
// TODO ext logical
|
||||
return uri;
|
||||
}
|
||||
exports.normalize = normalize;
|
||||
|
||||
|
||||
// this is very different from node's path.relative.
|
||||
// if uri starts with /, it's absolute uri, we don't relative it.
|
||||
// if base is `path/to/a', uri is `static/a.js`
|
||||
// relative is: ../../../static/a.js
|
||||
exports.relative = function(base, uri) {
|
||||
if (uri.charAt(0) === '/') return uri;
|
||||
|
||||
var bits = normalize(base).split('/');
|
||||
var dots = [];
|
||||
if (bits.length > 1) {
|
||||
bits.forEach(function() {
|
||||
dots.push('..');
|
||||
});
|
||||
dots.pop();
|
||||
return dots.join('/') + '/' + uri;
|
||||
}
|
||||
return uri;
|
||||
};
|
||||
|
||||
|
||||
// base is `arale/base/1.0.0/parser`
|
||||
// uri is `./base`
|
||||
// the result should be `arale/base/1.0.0/base`
|
||||
exports.absolute = function(base, uri) {
|
||||
if (uri.charAt(0) !== '.') return uri;
|
||||
uri = path.join(path.dirname(base), uri);
|
||||
return exports.normalize(uri);
|
||||
};
|
||||
|
||||
|
||||
exports.join = function(base, uri) {
|
||||
return path.join(base, uri).replace(/\\/g, '/');
|
||||
};
|
||||
|
||||
|
||||
exports.dirname = function(uri) {
|
||||
uri = path.dirname(uri);
|
||||
return uri.replace(/\\/g, '/');
|
||||
};
|
||||
|
||||
|
||||
exports.basename = function(uri) {
|
||||
var basename = path.basename(uri);
|
||||
return basename.replace(/\\/g, '/');
|
||||
};
|
||||
|
||||
|
||||
exports.extname = function(uri) {
|
||||
var ext = path.extname(uri);
|
||||
// default ext is js
|
||||
return ext ? ext: '.js';
|
||||
};
|
||||
|
||||
|
||||
exports.appendext = function(uri) {
|
||||
var ext = path.extname(uri);
|
||||
if (!ext) return uri + '.js';
|
||||
return uri;
|
||||
};
|
||||
|
||||
|
||||
exports.parseAlias = function(pkg, name) {
|
||||
// relative name: ./class
|
||||
if (name.charAt(0) === '.') {
|
||||
return name.replace(/\.js$/, '');
|
||||
}
|
||||
var alias = getAlias(pkg);
|
||||
if (alias.hasOwnProperty(name)) {
|
||||
return alias[name];
|
||||
}
|
||||
return name;
|
||||
};
|
||||
|
||||
|
||||
exports.isAlias = function(pkg, name) {
|
||||
var alias = getAlias(pkg);
|
||||
return alias.hasOwnProperty(name);
|
||||
};
|
||||
|
||||
|
||||
exports.idFromPackage = function(pkg, filename, format) {
|
||||
if (filename && !format && ~filename.indexOf('{{')) {
|
||||
format = filename;
|
||||
filename = '';
|
||||
}
|
||||
if (!filename) {
|
||||
filename = pkg.filename || '';
|
||||
}
|
||||
if (filename.charAt(0) === '.') {
|
||||
return filename.replace(/\.js$/, '');
|
||||
}
|
||||
if (pkg.spm && pkg.spm.format) {
|
||||
format = format || pkg.spm.format;
|
||||
}
|
||||
format = format || '{{family}}/{{name}}/{{version}}/{{filename}}';
|
||||
var data = pkg;
|
||||
data.filename = filename.replace(/\.js$/, '');
|
||||
return template(format, data);
|
||||
};
|
||||
|
||||
// validate if the format is the default format
|
||||
exports.validateFormat = function(format) {
|
||||
var regex = /^\{\{\s*family\s*\}\}\/\{\{\s*name\s*\}\}\/\{\{\s*version\s*\}\}\/\{\{\s*filename\s*\}\}$/;
|
||||
return regex.test(format);
|
||||
};
|
||||
|
||||
|
||||
function getAlias(pkg) {
|
||||
var alias = {};
|
||||
if (pkg.spm && pkg.spm.alias) {
|
||||
alias = pkg.spm.alias;
|
||||
} else if (pkg.alias) {
|
||||
alias = pkg.alias;
|
||||
}
|
||||
return alias;
|
||||
}
|
||||
|
||||
function template(format, data) {
|
||||
var regex = /\{\{\s*(.*?)\s*\}\}/g;
|
||||
var ret = format;
|
||||
var match = regex.exec(format);
|
||||
|
||||
var getData = function(obj, key) {
|
||||
var keys = key.split('.');
|
||||
keys.forEach(function(k) {
|
||||
if (obj && obj.hasOwnProperty(k)) {
|
||||
obj = obj[k];
|
||||
}
|
||||
});
|
||||
return obj || '';
|
||||
};
|
||||
|
||||
var placeholder, key, value;
|
||||
while (match) {
|
||||
placeholder = match[0], key = match[1];
|
||||
value = getData(data, key);
|
||||
ret = ret.replace(placeholder, value);
|
||||
match = regex.exec(format);
|
||||
}
|
||||
return ret;
|
||||
}
|
15
static/js/node_modules/grunt-cmd-concat/node_modules/cmd-util/node_modules/.bin/uglifyjs
generated
vendored
15
static/js/node_modules/grunt-cmd-concat/node_modules/cmd-util/node_modules/.bin/uglifyjs
generated
vendored
|
@ -1,15 +0,0 @@
|
|||
#!/bin/sh
|
||||
basedir=`dirname "$0"`
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
"$basedir/node" "$basedir/../uglify-js/bin/uglifyjs" "$@"
|
||||
ret=$?
|
||||
else
|
||||
node "$basedir/../uglify-js/bin/uglifyjs" "$@"
|
||||
ret=$?
|
||||
fi
|
||||
exit $ret
|
|
@ -1,6 +0,0 @@
|
|||
:: Created by npm, please don't edit manually.
|
||||
@IF EXIST "%~dp0\node.exe" (
|
||||
"%~dp0\node.exe" "%~dp0\..\uglify-js\bin\uglifyjs" %*
|
||||
) ELSE (
|
||||
node "%~dp0\..\uglify-js\bin\uglifyjs" %*
|
||||
)
|
|
@ -1,2 +0,0 @@
|
|||
tmp/
|
||||
node_modules/
|
|
@ -1,544 +0,0 @@
|
|||
UglifyJS 2
|
||||
==========
|
||||
|
||||
UglifyJS is a JavaScript parser, minifier, compressor or beautifier toolkit.
|
||||
|
||||
This page documents the command line utility. For
|
||||
[API and internals documentation see my website](http://lisperator.net/uglifyjs/).
|
||||
There's also an
|
||||
[in-browser online demo](http://lisperator.net/uglifyjs/#demo) (for Firefox,
|
||||
Chrome and probably Safari).
|
||||
|
||||
Install
|
||||
-------
|
||||
|
||||
First make sure you have installed the latest version of [node.js](http://nodejs.org/)
|
||||
(You may need to restart your computer after this step).
|
||||
|
||||
From NPM for use as a command line app:
|
||||
|
||||
npm install uglify-js -g
|
||||
|
||||
From NPM for programmatic use:
|
||||
|
||||
npm install uglify-js
|
||||
|
||||
From Git:
|
||||
|
||||
git clone git://github.com/mishoo/UglifyJS2.git
|
||||
cd UglifyJS2
|
||||
npm link .
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
uglifyjs [input files] [options]
|
||||
|
||||
UglifyJS2 can take multiple input files. It's recommended that you pass the
|
||||
input files first, then pass the options. UglifyJS will parse input files
|
||||
in sequence and apply any compression options. The files are parsed in the
|
||||
same global scope, that is, a reference from a file to some
|
||||
variable/function declared in another file will be matched properly.
|
||||
|
||||
If you want to read from STDIN instead, pass a single dash instead of input
|
||||
files.
|
||||
|
||||
The available options are:
|
||||
|
||||
--source-map Specify an output file where to generate source map.
|
||||
[string]
|
||||
--source-map-root The path to the original source to be included in the
|
||||
source map. [string]
|
||||
--source-map-url The path to the source map to be added in //@
|
||||
sourceMappingURL. Defaults to the value passed with
|
||||
--source-map. [string]
|
||||
--in-source-map Input source map, useful if you're compressing JS that was
|
||||
generated from some other original code.
|
||||
-p, --prefix Skip prefix for original filenames that appear in source
|
||||
maps. For example -p 3 will drop 3 directories from file
|
||||
names and ensure they are relative paths.
|
||||
-o, --output Output file (default STDOUT).
|
||||
-b, --beautify Beautify output/specify output options. [string]
|
||||
-m, --mangle Mangle names/pass mangler options. [string]
|
||||
-r, --reserved Reserved names to exclude from mangling.
|
||||
-c, --compress Enable compressor/pass compressor options. Pass options
|
||||
like -c hoist_vars=false,if_return=false. Use -c with no
|
||||
argument to use the default compression options. [string]
|
||||
-d, --define Global definitions [string]
|
||||
--comments Preserve copyright comments in the output. By default this
|
||||
works like Google Closure, keeping JSDoc-style comments
|
||||
that contain "@license" or "@preserve". You can optionally
|
||||
pass one of the following arguments to this flag:
|
||||
- "all" to keep all comments
|
||||
- a valid JS regexp (needs to start with a slash) to keep
|
||||
only comments that match.
|
||||
Note that currently not *all* comments can be kept when
|
||||
compression is on, because of dead code removal or
|
||||
cascading statements into sequences. [string]
|
||||
--stats Display operations run time on STDERR. [boolean]
|
||||
--acorn Use Acorn for parsing. [boolean]
|
||||
--spidermonkey Assume input fles are SpiderMonkey AST format (as JSON).
|
||||
[boolean]
|
||||
--self Build itself (UglifyJS2) as a library (implies
|
||||
--wrap=UglifyJS --export-all) [boolean]
|
||||
--wrap Embed everything in a big function, making the “exports”
|
||||
and “global” variables available. You need to pass an
|
||||
argument to this option to specify the name that your
|
||||
module will take when included in, say, a browser.
|
||||
[string]
|
||||
--export-all Only used when --wrap, this tells UglifyJS to add code to
|
||||
automatically export all globals. [boolean]
|
||||
--lint Display some scope warnings [boolean]
|
||||
-v, --verbose Verbose [boolean]
|
||||
-V, --version Print version number and exit. [boolean]
|
||||
|
||||
Specify `--output` (`-o`) to declare the output file. Otherwise the output
|
||||
goes to STDOUT.
|
||||
|
||||
## Source map options
|
||||
|
||||
UglifyJS2 can generate a source map file, which is highly useful for
|
||||
debugging your compressed JavaScript. To get a source map, pass
|
||||
`--source-map output.js.map` (full path to the file where you want the
|
||||
source map dumped).
|
||||
|
||||
Additionally you might need `--source-map-root` to pass the URL where the
|
||||
original files can be found. In case you are passing full paths to input
|
||||
files to UglifyJS, you can use `--prefix` (`-p`) to specify the number of
|
||||
directories to drop from the path prefix when declaring files in the source
|
||||
map.
|
||||
|
||||
For example:
|
||||
|
||||
uglifyjs /home/doe/work/foo/src/js/file1.js \
|
||||
/home/doe/work/foo/src/js/file2.js \
|
||||
-o foo.min.js \
|
||||
--source-map foo.min.js.map \
|
||||
--source-map-root http://foo.com/src \
|
||||
-p 5 -c -m
|
||||
|
||||
The above will compress and mangle `file1.js` and `file2.js`, will drop the
|
||||
output in `foo.min.js` and the source map in `foo.min.js.map`. The source
|
||||
mapping will refer to `http://foo.com/src/js/file1.js` and
|
||||
`http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src`
|
||||
as the source map root, and the original files as `js/file1.js` and
|
||||
`js/file2.js`).
|
||||
|
||||
### Composed source map
|
||||
|
||||
When you're compressing JS code that was output by a compiler such as
|
||||
CoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd
|
||||
like to map back to the original code (i.e. CoffeeScript). UglifyJS has an
|
||||
option to take an input source map. Assuming you have a mapping from
|
||||
CoffeeScript → compiled JS, UglifyJS can generate a map from CoffeeScript →
|
||||
compressed JS by mapping every token in the compiled JS to its original
|
||||
location.
|
||||
|
||||
To use this feature you need to pass `--in-source-map
|
||||
/path/to/input/source.map`. Normally the input source map should also point
|
||||
to the file containing the generated JS, so if that's correct you can omit
|
||||
input files from the command line.
|
||||
|
||||
## Mangler options
|
||||
|
||||
To enable the mangler you need to pass `--mangle` (`-m`). Optionally you
|
||||
can pass `-m sort=true` (we'll possibly have other flags in the future) in order
|
||||
to assign shorter names to most frequently used variables. This saves a few
|
||||
hundred bytes on jQuery before gzip, but the output is _bigger_ after gzip
|
||||
(and seems to happen for other libraries I tried it on) therefore it's not
|
||||
enabled by default.
|
||||
|
||||
When mangling is enabled but you want to prevent certain names from being
|
||||
mangled, you can declare those names with `--reserved` (`-r`) — pass a
|
||||
comma-separated list of names. For example:
|
||||
|
||||
uglifyjs ... -m -r '$,require,exports'
|
||||
|
||||
to prevent the `require`, `exports` and `$` names from being changed.
|
||||
|
||||
## Compressor options
|
||||
|
||||
You need to pass `--compress` (`-c`) to enable the compressor. Optionally
|
||||
you can pass a comma-separated list of options. Options are in the form
|
||||
`foo=bar`, or just `foo` (the latter implies a boolean option that you want
|
||||
to set `true`; it's effectively a shortcut for `foo=true`).
|
||||
|
||||
The defaults should be tuned for maximum compression on most code. Here are
|
||||
the available options (all are `true` by default, except `hoist_vars`):
|
||||
|
||||
- `sequences` -- join consecutive simple statements using the comma operator
|
||||
- `properties` -- rewrite property access using the dot notation, for
|
||||
example `foo["bar"] → foo.bar`
|
||||
- `dead_code` -- remove unreachable code
|
||||
- `drop_debugger` -- remove `debugger;` statements
|
||||
- `unsafe` -- apply "unsafe" transformations (discussion below)
|
||||
- `conditionals` -- apply optimizations for `if`-s and conditional
|
||||
expressions
|
||||
- `comparisons` -- apply certain optimizations to binary nodes, for example:
|
||||
`!(a <= b) → a > b` (only when `unsafe`), attempts to negate binary nodes,
|
||||
e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc.
|
||||
- `evaluate` -- attempt to evaluate constant expressions
|
||||
- `booleans` -- various optimizations for boolean context, for example `!!a
|
||||
? b : c → a ? b : c`
|
||||
- `loops` -- optimizations for `do`, `while` and `for` loops when we can
|
||||
statically determine the condition
|
||||
- `unused` -- drop unreferenced functions and variables
|
||||
- `hoist_funs` -- hoist function declarations
|
||||
- `hoist_vars` -- hoist `var` declarations (this is `false` by default
|
||||
because it seems to increase the size of the output in general)
|
||||
- `if_return` -- optimizations for if/return and if/continue
|
||||
- `join_vars` -- join consecutive `var` statements
|
||||
- `cascade` -- small optimization for sequences, transform `x, x` into `x`
|
||||
and `x = something(), x` into `x = something()`
|
||||
- `warnings` -- display warnings when dropping unreachable code or unused
|
||||
declarations etc.
|
||||
|
||||
### Conditional compilation
|
||||
|
||||
You can use the `--define` (`-d`) switch in order to declare global
|
||||
variables that UglifyJS will assume to be constants (unless defined in
|
||||
scope). For example if you pass `--define DEBUG=false` then, coupled with
|
||||
dead code removal UglifyJS will discard the following from the output:
|
||||
|
||||
if (DEBUG) {
|
||||
console.log("debug stuff");
|
||||
}
|
||||
|
||||
UglifyJS will warn about the condition being always false and about dropping
|
||||
unreachable code; for now there is no option to turn off only this specific
|
||||
warning, you can pass `warnings=false` to turn off *all* warnings.
|
||||
|
||||
Another way of doing that is to declare your globals as constants in a
|
||||
separate file and include it into the build. For example you can have a
|
||||
`build/defines.js` file with the following:
|
||||
|
||||
const DEBUG = false;
|
||||
const PRODUCTION = true;
|
||||
// etc.
|
||||
|
||||
and build your code like this:
|
||||
|
||||
uglifyjs build/defines.js js/foo.js js/bar.js... -c
|
||||
|
||||
UglifyJS will notice the constants and, since they cannot be altered, it
|
||||
will evaluate references to them to the value itself and drop unreachable
|
||||
code as usual. The possible downside of this approach is that the build
|
||||
will contain the `const` declarations.
|
||||
|
||||
<a name="codegen-options"></a>
|
||||
## Beautifier options
|
||||
|
||||
The code generator tries to output shortest code possible by default. In
|
||||
case you want beautified output, pass `--beautify` (`-b`). Optionally you
|
||||
can pass additional arguments that control the code output:
|
||||
|
||||
- `beautify` (default `true`) -- whether to actually beautify the output.
|
||||
Passing `-b` will set this to true, but you might need to pass `-b` even
|
||||
when you want to generate minified code, in order to specify additional
|
||||
arguments, so you can use `-b beautify=false` to override it.
|
||||
- `indent-level` (default 4)
|
||||
- `indent-start` (default 0) -- prefix all lines by that many spaces
|
||||
- `quote-keys` (default `false`) -- pass `true` to quote all keys in literal
|
||||
objects
|
||||
- `space-colon` (default `true`) -- insert a space after the colon signs
|
||||
- `ascii-only` (default `false`) -- escape Unicode characters in strings and
|
||||
regexps
|
||||
- `inline-script` (default `false`) -- escape the slash in occurrences of
|
||||
`</script` in strings
|
||||
- `width` (default 80) -- only takes effect when beautification is on, this
|
||||
specifies an (orientative) line width that the beautifier will try to
|
||||
obey. It refers to the width of the line text (excluding indentation).
|
||||
It doesn't work very well currently, but it does make the code generated
|
||||
by UglifyJS more readable.
|
||||
- `max-line-len` (default 32000) -- maximum line length (for uglified code)
|
||||
- `ie-proof` (default `true`) -- generate “IE-proof” code (for now this
|
||||
means add brackets around the do/while in code like this: `if (foo) do
|
||||
something(); while (bar); else ...`.
|
||||
- `bracketize` (default `false`) -- always insert brackets in `if`, `for`,
|
||||
`do`, `while` or `with` statements, even if their body is a single
|
||||
statement.
|
||||
- `semicolons` (default `true`) -- separate statements with semicolons. If
|
||||
you pass `false` then whenever possible we will use a newline instead of a
|
||||
semicolon, leading to more readable output of uglified code (size before
|
||||
gzip could be smaller; size after gzip insignificantly larger).
|
||||
|
||||
### Keeping copyright notices or other comments
|
||||
|
||||
You can pass `--comments` to retain certain comments in the output. By
|
||||
default it will keep JSDoc-style comments that contain "@preserve",
|
||||
"@license" or "@cc_on" (conditional compilation for IE). You can pass
|
||||
`--comments all` to keep all the comments, or a valid JavaScript regexp to
|
||||
keep only comments that match this regexp. For example `--comments
|
||||
'/foo|bar/'` will keep only comments that contain "foo" or "bar".
|
||||
|
||||
Note, however, that there might be situations where comments are lost. For
|
||||
example:
|
||||
|
||||
function f() {
|
||||
/** @preserve Foo Bar */
|
||||
function g() {
|
||||
// this function is never called
|
||||
}
|
||||
return something();
|
||||
}
|
||||
|
||||
Even though it has "@preserve", the comment will be lost because the inner
|
||||
function `g` (which is the AST node to which the comment is attached to) is
|
||||
discarded by the compressor as not referenced.
|
||||
|
||||
The safest comments where to place copyright information (or other info that
|
||||
needs to be kept in the output) are comments attached to toplevel nodes.
|
||||
|
||||
## Support for the SpiderMonkey AST
|
||||
|
||||
UglifyJS2 has its own abstract syntax tree format; for
|
||||
[practical reasons](http://lisperator.net/blog/uglifyjs-why-not-switching-to-spidermonkey-ast/)
|
||||
we can't easily change to using the SpiderMonkey AST internally. However,
|
||||
UglifyJS now has a converter which can import a SpiderMonkey AST.
|
||||
|
||||
For example [Acorn][acorn] is a super-fast parser that produces a
|
||||
SpiderMonkey AST. It has a small CLI utility that parses one file and dumps
|
||||
the AST in JSON on the standard output. To use UglifyJS to mangle and
|
||||
compress that:
|
||||
|
||||
acorn file.js | uglifyjs --spidermonkey -m -c
|
||||
|
||||
The `--spidermonkey` option tells UglifyJS that all input files are not
|
||||
JavaScript, but JS code described in SpiderMonkey AST in JSON. Therefore we
|
||||
don't use our own parser in this case, but just transform that AST into our
|
||||
internal AST.
|
||||
|
||||
### Use Acorn for parsing
|
||||
|
||||
More for fun, I added the `--acorn` option which will use Acorn to do all
|
||||
the parsing. If you pass this option, UglifyJS will `require("acorn")`.
|
||||
|
||||
Acorn is really fast (e.g. 250ms instead of 380ms on some 650K code), but
|
||||
converting the SpiderMonkey tree that Acorn produces takes another 150ms so
|
||||
in total it's a bit more than just using UglifyJS's own parser.
|
||||
|
||||
API Reference
|
||||
-------------
|
||||
|
||||
Assuming installation via NPM, you can load UglifyJS in your application
|
||||
like this:
|
||||
|
||||
var UglifyJS = require("uglify-js");
|
||||
|
||||
It exports a lot of names, but I'll discuss here the basics that are needed
|
||||
for parsing, mangling and compressing a piece of code. The sequence is (1)
|
||||
parse, (2) compress, (3) mangle, (4) generate output code.
|
||||
|
||||
### The simple way
|
||||
|
||||
There's a single toplevel function which combines all the steps. If you
|
||||
don't need additional customization, you might want to go with `minify`.
|
||||
Example:
|
||||
|
||||
var result = UglifyJS.minify("/path/to/file.js");
|
||||
console.log(result.code); // minified output
|
||||
// if you need to pass code instead of file name
|
||||
var result = UglifyJS.minify("var b = function () {};", {fromString: true});
|
||||
|
||||
You can also compress multiple files:
|
||||
|
||||
var result = UglifyJS.minify([ "file1.js", "file2.js", "file3.js" ]);
|
||||
console.log(result.code);
|
||||
|
||||
To generate a source map:
|
||||
|
||||
var result = UglifyJS.minify([ "file1.js", "file2.js", "file3.js" ], {
|
||||
outSourceMap: "out.js.map"
|
||||
});
|
||||
console.log(result.code); // minified output
|
||||
console.log(result.map);
|
||||
|
||||
Note that the source map is not saved in a file, it's just returned in
|
||||
`result.map`. The value passed for `outSourceMap` is only used to set the
|
||||
`file` attribute in the source map (see [the spec][sm-spec]).
|
||||
|
||||
You can also specify sourceRoot property to be included in source map:
|
||||
|
||||
var result = UglifyJS.minify([ "file1.js", "file2.js", "file3.js" ], {
|
||||
outSourceMap: "out.js.map",
|
||||
sourceRoot: "http://example.com/src"
|
||||
});
|
||||
|
||||
|
||||
If you're compressing compiled JavaScript and have a source map for it, you
|
||||
can use the `inSourceMap` argument:
|
||||
|
||||
var result = UglifyJS.minify("compiled.js", {
|
||||
inSourceMap: "compiled.js.map",
|
||||
outSourceMap: "minified.js.map"
|
||||
});
|
||||
// same as before, it returns `code` and `map`
|
||||
|
||||
The `inSourceMap` is only used if you also request `outSourceMap` (it makes
|
||||
no sense otherwise).
|
||||
|
||||
Other options:
|
||||
|
||||
- `warnings` (default `false`) — pass `true` to display compressor warnings.
|
||||
|
||||
- `fromString` (default `false`) — if you pass `true` then you can pass
|
||||
JavaScript source code, rather than file names.
|
||||
|
||||
- `mangle` — pass `false` to skip mangling names.
|
||||
|
||||
- `output` (default `null`) — pass an object if you wish to specify
|
||||
additional [output options][codegen]. The defaults are optimized
|
||||
for best compression.
|
||||
|
||||
- `compress` (default `{}`) — pass `false` to skip compressing entirely.
|
||||
Pass an object to specify custom [compressor options][compressor].
|
||||
|
||||
We could add more options to `UglifyJS.minify` — if you need additional
|
||||
functionality please suggest!
|
||||
|
||||
### The hard way
|
||||
|
||||
Following there's more detailed API info, in case the `minify` function is
|
||||
too simple for your needs.
|
||||
|
||||
#### The parser
|
||||
|
||||
var toplevel_ast = UglifyJS.parse(code, options);
|
||||
|
||||
`options` is optional and if present it must be an object. The following
|
||||
properties are available:
|
||||
|
||||
- `strict` — disable automatic semicolon insertion and support for trailing
|
||||
comma in arrays and objects
|
||||
- `filename` — the name of the file where this code is coming from
|
||||
- `toplevel` — a `toplevel` node (as returned by a previous invocation of
|
||||
`parse`)
|
||||
|
||||
The last two options are useful when you'd like to minify multiple files and
|
||||
get a single file as the output and a proper source map. Our CLI tool does
|
||||
something like this:
|
||||
|
||||
var toplevel = null;
|
||||
files.forEach(function(file){
|
||||
var code = fs.readFileSync(file);
|
||||
toplevel = UglifyJS.parse(code, {
|
||||
filename: file,
|
||||
toplevel: toplevel
|
||||
});
|
||||
});
|
||||
|
||||
After this, we have in `toplevel` a big AST containing all our files, with
|
||||
each token having proper information about where it came from.
|
||||
|
||||
#### Scope information
|
||||
|
||||
UglifyJS contains a scope analyzer that you need to call manually before
|
||||
compressing or mangling. Basically it augments various nodes in the AST
|
||||
with information about where is a name defined, how many times is a name
|
||||
referenced, if it is a global or not, if a function is using `eval` or the
|
||||
`with` statement etc. I will discuss this some place else, for now what's
|
||||
important to know is that you need to call the following before doing
|
||||
anything with the tree:
|
||||
|
||||
toplevel.figure_out_scope()
|
||||
|
||||
#### Compression
|
||||
|
||||
Like this:
|
||||
|
||||
var compressor = UglifyJS.Compressor(options);
|
||||
var compressed_ast = toplevel.transform(compressor);
|
||||
|
||||
The `options` can be missing. Available options are discussed above in
|
||||
“Compressor options”. Defaults should lead to best compression in most
|
||||
scripts.
|
||||
|
||||
The compressor is destructive, so don't rely that `toplevel` remains the
|
||||
original tree.
|
||||
|
||||
#### Mangling
|
||||
|
||||
After compression it is a good idea to call again `figure_out_scope` (since
|
||||
the compressor might drop unused variables / unreachable code and this might
|
||||
change the number of identifiers or their position). Optionally, you can
|
||||
call a trick that helps after Gzip (counting character frequency in
|
||||
non-mangleable words). Example:
|
||||
|
||||
compressed_ast.figure_out_scope();
|
||||
compressed_ast.compute_char_frequency();
|
||||
compressed_ast.mangle_names();
|
||||
|
||||
#### Generating output
|
||||
|
||||
AST nodes have a `print` method that takes an output stream. Essentially,
|
||||
to generate code you do this:
|
||||
|
||||
var stream = UglifyJS.OutputStream(options);
|
||||
compressed_ast.print(stream);
|
||||
var code = stream.toString(); // this is your minified code
|
||||
|
||||
or, for a shortcut you can do:
|
||||
|
||||
var code = compressed_ast.print_to_string(options);
|
||||
|
||||
As usual, `options` is optional. The output stream accepts a lot of otions,
|
||||
most of them documented above in section “Beautifier options”. The two
|
||||
which we care about here are `source_map` and `comments`.
|
||||
|
||||
#### Keeping comments in the output
|
||||
|
||||
In order to keep certain comments in the output you need to pass the
|
||||
`comments` option. Pass a RegExp or a function. If you pass a RegExp, only
|
||||
those comments whose body matches the regexp will be kept. Note that body
|
||||
means without the initial `//` or `/*`. If you pass a function, it will be
|
||||
called for every comment in the tree and will receive two arguments: the
|
||||
node that the comment is attached to, and the comment token itself.
|
||||
|
||||
The comment token has these properties:
|
||||
|
||||
- `type`: "comment1" for single-line comments or "comment2" for multi-line
|
||||
comments
|
||||
- `value`: the comment body
|
||||
- `pos` and `endpos`: the start/end positions (zero-based indexes) in the
|
||||
original code where this comment appears
|
||||
- `line` and `col`: the line and column where this comment appears in the
|
||||
original code
|
||||
- `file` — the file name of the original file
|
||||
- `nlb` — true if there was a newline before this comment in the original
|
||||
code, or if this comment contains a newline.
|
||||
|
||||
Your function should return `true` to keep the comment, or a falsy value
|
||||
otherwise.
|
||||
|
||||
#### Generating a source mapping
|
||||
|
||||
You need to pass the `source_map` argument when calling `print`. It needs
|
||||
to be a `SourceMap` object (which is a thin wrapper on top of the
|
||||
[source-map][source-map] library).
|
||||
|
||||
Example:
|
||||
|
||||
var source_map = UglifyJS.SourceMap(source_map_options);
|
||||
var stream = UglifyJS.OutputStream({
|
||||
...
|
||||
source_map: source_map
|
||||
});
|
||||
compressed_ast.print(stream);
|
||||
|
||||
var code = stream.toString();
|
||||
var map = source_map.toString(); // json output for your source map
|
||||
|
||||
The `source_map_options` (optional) can contain the following properties:
|
||||
|
||||
- `file`: the name of the JavaScript output file that this mapping refers to
|
||||
- `root`: the `sourceRoot` property (see the [spec][sm-spec])
|
||||
- `orig`: the "original source map", handy when you compress generated JS
|
||||
and want to map the minified output back to the original code where it
|
||||
came from. It can be simply a string in JSON, or a JSON object containing
|
||||
the original source map.
|
||||
|
||||
[acorn]: https://github.com/marijnh/acorn
|
||||
[source-map]: https://github.com/mozilla/source-map
|
||||
[sm-spec]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
|
||||
[codegen]: http://lisperator.net/uglifyjs/codegen
|
||||
[compressor]: http://lisperator.net/uglifyjs/compress
|
|
@ -1,370 +0,0 @@
|
|||
#! /usr/bin/env node
|
||||
// -*- js -*-
|
||||
|
||||
"use strict";
|
||||
|
||||
var UglifyJS = require("../tools/node");
|
||||
var sys = require("util");
|
||||
var optimist = require("optimist");
|
||||
var fs = require("fs");
|
||||
var acorn;
|
||||
var ARGS = optimist
|
||||
.usage("$0 input1.js [input2.js ...] [options]\n\
|
||||
Use a single dash to read input from the standard input.\
|
||||
\n\n\
|
||||
NOTE: by default there is no mangling/compression.\n\
|
||||
Without [options] it will simply parse input files and dump the AST\n\
|
||||
with whitespace and comments discarded. To achieve compression and\n\
|
||||
mangling you need to use `-c` and `-m`.\
|
||||
")
|
||||
.describe("source-map", "Specify an output file where to generate source map.")
|
||||
.describe("source-map-root", "The path to the original source to be included in the source map.")
|
||||
.describe("source-map-url", "The path to the source map to be added in //@ sourceMappingURL. Defaults to the value passed with --source-map.")
|
||||
.describe("in-source-map", "Input source map, useful if you're compressing JS that was generated from some other original code.")
|
||||
.describe("p", "Skip prefix for original filenames that appear in source maps. \
|
||||
For example -p 3 will drop 3 directories from file names and ensure they are relative paths.")
|
||||
.describe("o", "Output file (default STDOUT).")
|
||||
.describe("b", "Beautify output/specify output options.")
|
||||
.describe("m", "Mangle names/pass mangler options.")
|
||||
.describe("r", "Reserved names to exclude from mangling.")
|
||||
.describe("c", "Enable compressor/pass compressor options. \
|
||||
Pass options like -c hoist_vars=false,if_return=false. \
|
||||
Use -c with no argument to use the default compression options.")
|
||||
.describe("d", "Global definitions")
|
||||
|
||||
.describe("comments", "Preserve copyright comments in the output. \
|
||||
By default this works like Google Closure, keeping JSDoc-style comments that contain \"@license\" or \"@preserve\". \
|
||||
You can optionally pass one of the following arguments to this flag:\n\
|
||||
- \"all\" to keep all comments\n\
|
||||
- a valid JS regexp (needs to start with a slash) to keep only comments that match.\n\
|
||||
\
|
||||
Note that currently not *all* comments can be kept when compression is on, \
|
||||
because of dead code removal or cascading statements into sequences.")
|
||||
|
||||
.describe("stats", "Display operations run time on STDERR.")
|
||||
.describe("acorn", "Use Acorn for parsing.")
|
||||
.describe("spidermonkey", "Assume input fles are SpiderMonkey AST format (as JSON).")
|
||||
.describe("self", "Build itself (UglifyJS2) as a library (implies --wrap=UglifyJS --export-all)")
|
||||
.describe("wrap", "Embed everything in a big function, making the “exports” and “global” variables available. \
|
||||
You need to pass an argument to this option to specify the name that your module will take when included in, say, a browser.")
|
||||
.describe("export-all", "Only used when --wrap, this tells UglifyJS to add code to automatically export all globals.")
|
||||
.describe("lint", "Display some scope warnings")
|
||||
.describe("v", "Verbose")
|
||||
.describe("V", "Print version number and exit.")
|
||||
|
||||
.alias("p", "prefix")
|
||||
.alias("o", "output")
|
||||
.alias("v", "verbose")
|
||||
.alias("b", "beautify")
|
||||
.alias("m", "mangle")
|
||||
.alias("c", "compress")
|
||||
.alias("d", "define")
|
||||
.alias("r", "reserved")
|
||||
.alias("V", "version")
|
||||
|
||||
.string("source-map")
|
||||
.string("source-map-root")
|
||||
.string("source-map-url")
|
||||
.string("b")
|
||||
.string("m")
|
||||
.string("c")
|
||||
.string("d")
|
||||
.string("comments")
|
||||
.string("wrap")
|
||||
.boolean("export-all")
|
||||
.boolean("self")
|
||||
.boolean("v")
|
||||
.boolean("stats")
|
||||
.boolean("acorn")
|
||||
.boolean("spidermonkey")
|
||||
.boolean("lint")
|
||||
.boolean("V")
|
||||
|
||||
.wrap(80)
|
||||
|
||||
.argv
|
||||
;
|
||||
|
||||
normalize(ARGS);
|
||||
|
||||
if (ARGS.version || ARGS.V) {
|
||||
var json = require("../package.json");
|
||||
sys.puts(json.name + ' ' + json.version);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (ARGS.ast_help) {
|
||||
var desc = UglifyJS.describe_ast();
|
||||
sys.puts(typeof desc == "string" ? desc : JSON.stringify(desc, null, 2));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (ARGS.h || ARGS.help) {
|
||||
sys.puts(optimist.help());
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (ARGS.acorn) {
|
||||
acorn = require("acorn");
|
||||
}
|
||||
|
||||
var COMPRESS = getOptions("c", true);
|
||||
var MANGLE = getOptions("m", true);
|
||||
var BEAUTIFY = getOptions("b", true);
|
||||
|
||||
if (COMPRESS && ARGS.d) {
|
||||
COMPRESS.global_defs = getOptions("d");
|
||||
}
|
||||
|
||||
if (MANGLE && ARGS.r) {
|
||||
MANGLE.except = ARGS.r.replace(/^\s+|\s+$/g).split(/\s*,+\s*/);
|
||||
}
|
||||
|
||||
var OUTPUT_OPTIONS = {
|
||||
beautify: BEAUTIFY ? true : false
|
||||
};
|
||||
|
||||
if (BEAUTIFY)
|
||||
UglifyJS.merge(OUTPUT_OPTIONS, BEAUTIFY);
|
||||
|
||||
if (ARGS.comments) {
|
||||
if (/^\//.test(ARGS.comments)) {
|
||||
OUTPUT_OPTIONS.comments = new Function("return(" + ARGS.comments + ")")();
|
||||
} else if (ARGS.comments == "all") {
|
||||
OUTPUT_OPTIONS.comments = true;
|
||||
} else {
|
||||
OUTPUT_OPTIONS.comments = function(node, comment) {
|
||||
var text = comment.value;
|
||||
var type = comment.type;
|
||||
if (type == "comment2") {
|
||||
// multiline comment
|
||||
return /@preserve|@license|@cc_on/i.test(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var files = ARGS._.slice();
|
||||
|
||||
if (ARGS.self) {
|
||||
if (files.length > 0) {
|
||||
sys.error("WARN: Ignoring input files since --self was passed");
|
||||
}
|
||||
files = UglifyJS.FILES;
|
||||
if (!ARGS.wrap) ARGS.wrap = "UglifyJS";
|
||||
ARGS.export_all = true;
|
||||
}
|
||||
|
||||
var ORIG_MAP = ARGS.in_source_map;
|
||||
|
||||
if (ORIG_MAP) {
|
||||
ORIG_MAP = JSON.parse(fs.readFileSync(ORIG_MAP));
|
||||
if (files.length == 0) {
|
||||
sys.error("INFO: Using file from the input source map: " + ORIG_MAP.file);
|
||||
files = [ ORIG_MAP.file ];
|
||||
}
|
||||
if (ARGS.source_map_root == null) {
|
||||
ARGS.source_map_root = ORIG_MAP.sourceRoot;
|
||||
}
|
||||
}
|
||||
|
||||
if (files.length == 0) {
|
||||
files = [ "-" ];
|
||||
}
|
||||
|
||||
if (files.indexOf("-") >= 0 && ARGS.source_map) {
|
||||
sys.error("ERROR: Source map doesn't work with input from STDIN");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (files.filter(function(el){ return el == "-" }).length > 1) {
|
||||
sys.error("ERROR: Can read a single file from STDIN (two or more dashes specified)");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
var STATS = {};
|
||||
var OUTPUT_FILE = ARGS.o;
|
||||
var TOPLEVEL = null;
|
||||
|
||||
var SOURCE_MAP = ARGS.source_map ? UglifyJS.SourceMap({
|
||||
file: OUTPUT_FILE,
|
||||
root: ARGS.source_map_root,
|
||||
orig: ORIG_MAP,
|
||||
}) : null;
|
||||
|
||||
OUTPUT_OPTIONS.source_map = SOURCE_MAP;
|
||||
|
||||
try {
|
||||
var output = UglifyJS.OutputStream(OUTPUT_OPTIONS);
|
||||
var compressor = COMPRESS && UglifyJS.Compressor(COMPRESS);
|
||||
} catch(ex) {
|
||||
if (ex instanceof UglifyJS.DefaultsError) {
|
||||
sys.error(ex.msg);
|
||||
sys.error("Supported options:");
|
||||
sys.error(sys.inspect(ex.defs));
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
files.forEach(function(file) {
|
||||
var code = read_whole_file(file);
|
||||
if (ARGS.p != null) {
|
||||
file = file.replace(/^\/+/, "").split(/\/+/).slice(ARGS.p).join("/");
|
||||
}
|
||||
time_it("parse", function(){
|
||||
if (ARGS.spidermonkey) {
|
||||
var program = JSON.parse(code);
|
||||
if (!TOPLEVEL) TOPLEVEL = program;
|
||||
else TOPLEVEL.body = TOPLEVEL.body.concat(program.body);
|
||||
}
|
||||
else if (ARGS.acorn) {
|
||||
TOPLEVEL = acorn.parse(code, {
|
||||
locations : true,
|
||||
trackComments : true,
|
||||
sourceFile : file,
|
||||
program : TOPLEVEL
|
||||
});
|
||||
}
|
||||
else {
|
||||
TOPLEVEL = UglifyJS.parse(code, {
|
||||
filename: file,
|
||||
toplevel: TOPLEVEL
|
||||
});
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
if (ARGS.acorn || ARGS.spidermonkey) time_it("convert_ast", function(){
|
||||
TOPLEVEL = UglifyJS.AST_Node.from_mozilla_ast(TOPLEVEL);
|
||||
});
|
||||
|
||||
if (ARGS.wrap) {
|
||||
TOPLEVEL = TOPLEVEL.wrap_commonjs(ARGS.wrap, ARGS.export_all);
|
||||
}
|
||||
|
||||
var SCOPE_IS_NEEDED = COMPRESS || MANGLE || ARGS.lint;
|
||||
|
||||
if (SCOPE_IS_NEEDED) {
|
||||
time_it("scope", function(){
|
||||
TOPLEVEL.figure_out_scope();
|
||||
if (ARGS.lint) {
|
||||
TOPLEVEL.scope_warnings();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (COMPRESS) {
|
||||
time_it("squeeze", function(){
|
||||
TOPLEVEL = TOPLEVEL.transform(compressor);
|
||||
});
|
||||
}
|
||||
|
||||
if (SCOPE_IS_NEEDED) {
|
||||
time_it("scope", function(){
|
||||
TOPLEVEL.figure_out_scope();
|
||||
if (MANGLE) {
|
||||
TOPLEVEL.compute_char_frequency(MANGLE);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (MANGLE) time_it("mangle", function(){
|
||||
TOPLEVEL.mangle_names(MANGLE);
|
||||
});
|
||||
time_it("generate", function(){
|
||||
TOPLEVEL.print(output);
|
||||
});
|
||||
|
||||
output = output.get();
|
||||
|
||||
if (SOURCE_MAP) {
|
||||
fs.writeFileSync(ARGS.source_map, SOURCE_MAP, "utf8");
|
||||
output += "\n/*\n//@ sourceMappingURL=" + (ARGS.source_map_url || ARGS.source_map) + "\n*/";
|
||||
}
|
||||
|
||||
if (OUTPUT_FILE) {
|
||||
fs.writeFileSync(OUTPUT_FILE, output, "utf8");
|
||||
} else {
|
||||
sys.print(output);
|
||||
sys.error("\n");
|
||||
}
|
||||
|
||||
if (ARGS.stats) {
|
||||
sys.error(UglifyJS.string_template("Timing information (compressed {count} files):", {
|
||||
count: files.length
|
||||
}));
|
||||
for (var i in STATS) if (STATS.hasOwnProperty(i)) {
|
||||
sys.error(UglifyJS.string_template("- {name}: {time}s", {
|
||||
name: i,
|
||||
time: (STATS[i] / 1000).toFixed(3)
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/* -----[ functions ]----- */
|
||||
|
||||
function normalize(o) {
|
||||
for (var i in o) if (o.hasOwnProperty(i) && /-/.test(i)) {
|
||||
o[i.replace(/-/g, "_")] = o[i];
|
||||
delete o[i];
|
||||
}
|
||||
}
|
||||
|
||||
function getOptions(x, constants) {
|
||||
x = ARGS[x];
|
||||
if (!x) return null;
|
||||
var ret = {};
|
||||
if (x !== true) {
|
||||
var ast;
|
||||
try {
|
||||
ast = UglifyJS.parse(x);
|
||||
} catch(ex) {
|
||||
if (ex instanceof UglifyJS.JS_Parse_Error) {
|
||||
sys.error("Error parsing arguments in: " + x);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
ast.walk(new UglifyJS.TreeWalker(function(node){
|
||||
if (node instanceof UglifyJS.AST_Toplevel) return; // descend
|
||||
if (node instanceof UglifyJS.AST_SimpleStatement) return; // descend
|
||||
if (node instanceof UglifyJS.AST_Seq) return; // descend
|
||||
if (node instanceof UglifyJS.AST_Assign) {
|
||||
var name = node.left.print_to_string({ beautify: false }).replace(/-/g, "_");
|
||||
var value = node.right;
|
||||
if (constants)
|
||||
value = new Function("return (" + value.print_to_string() + ")")();
|
||||
ret[name] = value;
|
||||
return true; // no descend
|
||||
}
|
||||
sys.error(node.TYPE)
|
||||
sys.error("Error parsing arguments in: " + x);
|
||||
process.exit(1);
|
||||
}));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
function read_whole_file(filename) {
|
||||
if (filename == "-") {
|
||||
// XXX: this sucks. How does one read the whole STDIN
|
||||
// synchronously?
|
||||
filename = "/dev/stdin";
|
||||
}
|
||||
try {
|
||||
return fs.readFileSync(filename, "utf8");
|
||||
} catch(ex) {
|
||||
sys.error("ERROR: can't read file: " + filename);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function time_it(name, cont) {
|
||||
var t1 = new Date().getTime();
|
||||
var ret = cont();
|
||||
if (ARGS.stats) {
|
||||
var spent = new Date().getTime() - t1;
|
||||
if (STATS[name]) STATS[name] += spent;
|
||||
else STATS[name] = spent;
|
||||
}
|
||||
return ret;
|
||||
}
|
|
@ -1,964 +0,0 @@
|
|||
/***********************************************************************
|
||||
|
||||
A JavaScript tokenizer / parser / beautifier / compressor.
|
||||
https://github.com/mishoo/UglifyJS2
|
||||
|
||||
-------------------------------- (C) ---------------------------------
|
||||
|
||||
Author: Mihai Bazon
|
||||
<mihai.bazon@gmail.com>
|
||||
http://mihai.bazon.net/blog
|
||||
|
||||
Distributed under the BSD license:
|
||||
|
||||
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
* Redistributions of source code must retain the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials
|
||||
provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
|
||||
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
||||
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
|
||||
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGE.
|
||||
|
||||
***********************************************************************/
|
||||
|
||||
"use strict";
|
||||
|
||||
function DEFNODE(type, props, methods, base) {
|
||||
if (arguments.length < 4) base = AST_Node;
|
||||
if (!props) props = [];
|
||||
else props = props.split(/\s+/);
|
||||
var self_props = props;
|
||||
if (base && base.PROPS)
|
||||
props = props.concat(base.PROPS);
|
||||
var code = "return function AST_" + type + "(props){ if (props) { ";
|
||||
for (var i = props.length; --i >= 0;) {
|
||||
code += "this." + props[i] + " = props." + props[i] + ";";
|
||||
}
|
||||
var proto = base && new base;
|
||||
if (proto && proto.initialize || (methods && methods.initialize))
|
||||
code += "this.initialize();";
|
||||
code += "}}";
|
||||
var ctor = new Function(code)();
|
||||
if (proto) {
|
||||
ctor.prototype = proto;
|
||||
ctor.BASE = base;
|
||||
}
|
||||
if (base) base.SUBCLASSES.push(ctor);
|
||||
ctor.prototype.CTOR = ctor;
|
||||
ctor.PROPS = props || null;
|
||||
ctor.SELF_PROPS = self_props;
|
||||
ctor.SUBCLASSES = [];
|
||||
if (type) {
|
||||
ctor.prototype.TYPE = ctor.TYPE = type;
|
||||
}
|
||||
if (methods) for (i in methods) if (methods.hasOwnProperty(i)) {
|
||||
if (/^\$/.test(i)) {
|
||||
ctor[i.substr(1)] = methods[i];
|
||||
} else {
|
||||
ctor.prototype[i] = methods[i];
|
||||
}
|
||||
}
|
||||
ctor.DEFMETHOD = function(name, method) {
|
||||
this.prototype[name] = method;
|
||||
};
|
||||
return ctor;
|
||||
};
|
||||
|
||||
var AST_Token = DEFNODE("Token", "type value line col pos endpos nlb comments_before file", {
|
||||
}, null);
|
||||
|
||||
var AST_Node = DEFNODE("Node", "start end", {
|
||||
clone: function() {
|
||||
return new this.CTOR(this);
|
||||
},
|
||||
$documentation: "Base class of all AST nodes",
|
||||
$propdoc: {
|
||||
start: "[AST_Token] The first token of this node",
|
||||
end: "[AST_Token] The last token of this node"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this);
|
||||
},
|
||||
walk: function(visitor) {
|
||||
return this._walk(visitor); // not sure the indirection will be any help
|
||||
}
|
||||
}, null);
|
||||
|
||||
AST_Node.warn_function = null;
|
||||
AST_Node.warn = function(txt, props) {
|
||||
if (AST_Node.warn_function)
|
||||
AST_Node.warn_function(string_template(txt, props));
|
||||
};
|
||||
|
||||
/* -----[ statements ]----- */
|
||||
|
||||
var AST_Statement = DEFNODE("Statement", null, {
|
||||
$documentation: "Base class of all statements",
|
||||
});
|
||||
|
||||
var AST_Debugger = DEFNODE("Debugger", null, {
|
||||
$documentation: "Represents a debugger statement",
|
||||
}, AST_Statement);
|
||||
|
||||
var AST_Directive = DEFNODE("Directive", "value scope", {
|
||||
$documentation: "Represents a directive, like \"use strict\";",
|
||||
$propdoc: {
|
||||
value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
|
||||
scope: "[AST_Scope/S] The scope that this directive affects"
|
||||
},
|
||||
}, AST_Statement);
|
||||
|
||||
var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
|
||||
$documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
|
||||
$propdoc: {
|
||||
body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.body._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_Statement);
|
||||
|
||||
function walk_body(node, visitor) {
|
||||
if (node.body instanceof AST_Statement) {
|
||||
node.body._walk(visitor);
|
||||
}
|
||||
else node.body.forEach(function(stat){
|
||||
stat._walk(visitor);
|
||||
});
|
||||
};
|
||||
|
||||
var AST_Block = DEFNODE("Block", "body", {
|
||||
$documentation: "A body of statements (usually bracketed)",
|
||||
$propdoc: {
|
||||
body: "[AST_Statement*] an array of statements"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
walk_body(this, visitor);
|
||||
});
|
||||
}
|
||||
}, AST_Statement);
|
||||
|
||||
var AST_BlockStatement = DEFNODE("BlockStatement", null, {
|
||||
$documentation: "A block statement",
|
||||
}, AST_Block);
|
||||
|
||||
var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
|
||||
$documentation: "The empty statement (empty block or simply a semicolon)",
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this);
|
||||
}
|
||||
}, AST_Statement);
|
||||
|
||||
var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
|
||||
$documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
|
||||
$propdoc: {
|
||||
body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.body._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_Statement);
|
||||
|
||||
var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
|
||||
$documentation: "Statement with a label",
|
||||
$propdoc: {
|
||||
label: "[AST_Label] a label definition"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.label._walk(visitor);
|
||||
this.body._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_StatementWithBody);
|
||||
|
||||
var AST_DWLoop = DEFNODE("DWLoop", "condition", {
|
||||
$documentation: "Base class for do/while statements",
|
||||
$propdoc: {
|
||||
condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.condition._walk(visitor);
|
||||
this.body._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_StatementWithBody);
|
||||
|
||||
var AST_Do = DEFNODE("Do", null, {
|
||||
$documentation: "A `do` statement",
|
||||
}, AST_DWLoop);
|
||||
|
||||
var AST_While = DEFNODE("While", null, {
|
||||
$documentation: "A `while` statement",
|
||||
}, AST_DWLoop);
|
||||
|
||||
var AST_For = DEFNODE("For", "init condition step", {
|
||||
$documentation: "A `for` statement",
|
||||
$propdoc: {
|
||||
init: "[AST_Node?] the `for` initialization code, or null if empty",
|
||||
condition: "[AST_Node?] the `for` termination clause, or null if empty",
|
||||
step: "[AST_Node?] the `for` update clause, or null if empty"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
if (this.init) this.init._walk(visitor);
|
||||
if (this.condition) this.condition._walk(visitor);
|
||||
if (this.step) this.step._walk(visitor);
|
||||
this.body._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_StatementWithBody);
|
||||
|
||||
var AST_ForIn = DEFNODE("ForIn", "init name object", {
|
||||
$documentation: "A `for ... in` statement",
|
||||
$propdoc: {
|
||||
init: "[AST_Node] the `for/in` initialization code",
|
||||
name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var",
|
||||
object: "[AST_Node] the object that we're looping through"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.init._walk(visitor);
|
||||
this.object._walk(visitor);
|
||||
this.body._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_StatementWithBody);
|
||||
|
||||
var AST_With = DEFNODE("With", "expression", {
|
||||
$documentation: "A `with` statement",
|
||||
$propdoc: {
|
||||
expression: "[AST_Node] the `with` expression"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.expression._walk(visitor);
|
||||
this.body._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_StatementWithBody);
|
||||
|
||||
/* -----[ scope and functions ]----- */
|
||||
|
||||
var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", {
|
||||
$documentation: "Base class for all statements introducing a lexical scope",
|
||||
$propdoc: {
|
||||
directives: "[string*/S] an array of directives declared in this scope",
|
||||
variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
|
||||
functions: "[Object/S] like `variables`, but only lists function declarations",
|
||||
uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
|
||||
uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
|
||||
parent_scope: "[AST_Scope?/S] link to the parent scope",
|
||||
enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
|
||||
cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
|
||||
},
|
||||
}, AST_Block);
|
||||
|
||||
var AST_Toplevel = DEFNODE("Toplevel", "globals", {
|
||||
$documentation: "The toplevel scope",
|
||||
$propdoc: {
|
||||
globals: "[Object/S] a map of name -> SymbolDef for all undeclared names",
|
||||
},
|
||||
wrap_commonjs: function(name, export_all) {
|
||||
var self = this;
|
||||
var to_export = [];
|
||||
if (export_all) {
|
||||
self.figure_out_scope();
|
||||
self.walk(new TreeWalker(function(node){
|
||||
if (node instanceof AST_SymbolDeclaration && node.definition().global) {
|
||||
if (!find_if(function(n){ return n.name == node.name }, to_export))
|
||||
to_export.push(node);
|
||||
}
|
||||
}));
|
||||
}
|
||||
var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))";
|
||||
wrapped_tl = parse(wrapped_tl);
|
||||
wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
|
||||
if (node instanceof AST_SimpleStatement) {
|
||||
node = node.body;
|
||||
if (node instanceof AST_String) switch (node.getValue()) {
|
||||
case "$ORIG":
|
||||
return MAP.splice(self.body);
|
||||
case "$EXPORTS":
|
||||
var body = [];
|
||||
to_export.forEach(function(sym){
|
||||
body.push(new AST_SimpleStatement({
|
||||
body: new AST_Assign({
|
||||
left: new AST_Sub({
|
||||
expression: new AST_SymbolRef({ name: "exports" }),
|
||||
property: new AST_String({ value: sym.name }),
|
||||
}),
|
||||
operator: "=",
|
||||
right: new AST_SymbolRef(sym),
|
||||
}),
|
||||
}));
|
||||
});
|
||||
return MAP.splice(body);
|
||||
}
|
||||
}
|
||||
}));
|
||||
return wrapped_tl;
|
||||
}
|
||||
}, AST_Scope);
|
||||
|
||||
var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", {
|
||||
$documentation: "Base class for functions",
|
||||
$propdoc: {
|
||||
name: "[AST_SymbolDeclaration?] the name of this function",
|
||||
argnames: "[AST_SymbolFunarg*] array of function arguments",
|
||||
uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
if (this.name) this.name._walk(visitor);
|
||||
this.argnames.forEach(function(arg){
|
||||
arg._walk(visitor);
|
||||
});
|
||||
walk_body(this, visitor);
|
||||
});
|
||||
}
|
||||
}, AST_Scope);
|
||||
|
||||
var AST_Accessor = DEFNODE("Accessor", null, {
|
||||
$documentation: "A setter/getter function"
|
||||
}, AST_Lambda);
|
||||
|
||||
var AST_Function = DEFNODE("Function", null, {
|
||||
$documentation: "A function expression"
|
||||
}, AST_Lambda);
|
||||
|
||||
var AST_Defun = DEFNODE("Defun", null, {
|
||||
$documentation: "A function definition"
|
||||
}, AST_Lambda);
|
||||
|
||||
/* -----[ JUMPS ]----- */
|
||||
|
||||
var AST_Jump = DEFNODE("Jump", null, {
|
||||
$documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
|
||||
}, AST_Statement);
|
||||
|
||||
var AST_Exit = DEFNODE("Exit", "value", {
|
||||
$documentation: "Base class for “exits” (`return` and `throw`)",
|
||||
$propdoc: {
|
||||
value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, this.value && function(){
|
||||
this.value._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_Jump);
|
||||
|
||||
var AST_Return = DEFNODE("Return", null, {
|
||||
$documentation: "A `return` statement"
|
||||
}, AST_Exit);
|
||||
|
||||
var AST_Throw = DEFNODE("Throw", null, {
|
||||
$documentation: "A `throw` statement"
|
||||
}, AST_Exit);
|
||||
|
||||
var AST_LoopControl = DEFNODE("LoopControl", "label", {
|
||||
$documentation: "Base class for loop control statements (`break` and `continue`)",
|
||||
$propdoc: {
|
||||
label: "[AST_LabelRef?] the label, or null if none",
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, this.label && function(){
|
||||
this.label._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_Jump);
|
||||
|
||||
var AST_Break = DEFNODE("Break", null, {
|
||||
$documentation: "A `break` statement"
|
||||
}, AST_LoopControl);
|
||||
|
||||
var AST_Continue = DEFNODE("Continue", null, {
|
||||
$documentation: "A `continue` statement"
|
||||
}, AST_LoopControl);
|
||||
|
||||
/* -----[ IF ]----- */
|
||||
|
||||
var AST_If = DEFNODE("If", "condition alternative", {
|
||||
$documentation: "A `if` statement",
|
||||
$propdoc: {
|
||||
condition: "[AST_Node] the `if` condition",
|
||||
alternative: "[AST_Statement?] the `else` part, or null if not present"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.condition._walk(visitor);
|
||||
this.body._walk(visitor);
|
||||
if (this.alternative) this.alternative._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_StatementWithBody);
|
||||
|
||||
/* -----[ SWITCH ]----- */
|
||||
|
||||
var AST_Switch = DEFNODE("Switch", "expression", {
|
||||
$documentation: "A `switch` statement",
|
||||
$propdoc: {
|
||||
expression: "[AST_Node] the `switch` “discriminant”"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.expression._walk(visitor);
|
||||
walk_body(this, visitor);
|
||||
});
|
||||
}
|
||||
}, AST_Block);
|
||||
|
||||
var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
|
||||
$documentation: "Base class for `switch` branches",
|
||||
}, AST_Block);
|
||||
|
||||
var AST_Default = DEFNODE("Default", null, {
|
||||
$documentation: "A `default` switch branch",
|
||||
}, AST_SwitchBranch);
|
||||
|
||||
var AST_Case = DEFNODE("Case", "expression", {
|
||||
$documentation: "A `case` switch branch",
|
||||
$propdoc: {
|
||||
expression: "[AST_Node] the `case` expression"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.expression._walk(visitor);
|
||||
walk_body(this, visitor);
|
||||
});
|
||||
}
|
||||
}, AST_SwitchBranch);
|
||||
|
||||
/* -----[ EXCEPTIONS ]----- */
|
||||
|
||||
var AST_Try = DEFNODE("Try", "bcatch bfinally", {
|
||||
$documentation: "A `try` statement",
|
||||
$propdoc: {
|
||||
bcatch: "[AST_Catch?] the catch block, or null if not present",
|
||||
bfinally: "[AST_Finally?] the finally block, or null if not present"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
walk_body(this, visitor);
|
||||
if (this.bcatch) this.bcatch._walk(visitor);
|
||||
if (this.bfinally) this.bfinally._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_Block);
|
||||
|
||||
// XXX: this is wrong according to ECMA-262 (12.4). the catch block
|
||||
// should introduce another scope, as the argname should be visible
|
||||
// only inside the catch block. However, doing it this way because of
|
||||
// IE which simply introduces the name in the surrounding scope. If
|
||||
// we ever want to fix this then AST_Catch should inherit from
|
||||
// AST_Scope.
|
||||
var AST_Catch = DEFNODE("Catch", "argname", {
|
||||
$documentation: "A `catch` node; only makes sense as part of a `try` statement",
|
||||
$propdoc: {
|
||||
argname: "[AST_SymbolCatch] symbol for the exception"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.argname._walk(visitor);
|
||||
walk_body(this, visitor);
|
||||
});
|
||||
}
|
||||
}, AST_Block);
|
||||
|
||||
var AST_Finally = DEFNODE("Finally", null, {
|
||||
$documentation: "A `finally` node; only makes sense as part of a `try` statement"
|
||||
}, AST_Block);
|
||||
|
||||
/* -----[ VAR/CONST ]----- */
|
||||
|
||||
var AST_Definitions = DEFNODE("Definitions", "definitions", {
|
||||
$documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)",
|
||||
$propdoc: {
|
||||
definitions: "[AST_VarDef*] array of variable definitions"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.definitions.forEach(function(def){
|
||||
def._walk(visitor);
|
||||
});
|
||||
});
|
||||
}
|
||||
}, AST_Statement);
|
||||
|
||||
var AST_Var = DEFNODE("Var", null, {
|
||||
$documentation: "A `var` statement"
|
||||
}, AST_Definitions);
|
||||
|
||||
var AST_Const = DEFNODE("Const", null, {
|
||||
$documentation: "A `const` statement"
|
||||
}, AST_Definitions);
|
||||
|
||||
var AST_VarDef = DEFNODE("VarDef", "name value", {
|
||||
$documentation: "A variable declaration; only appears in a AST_Definitions node",
|
||||
$propdoc: {
|
||||
name: "[AST_SymbolVar|AST_SymbolConst] name of the variable",
|
||||
value: "[AST_Node?] initializer, or null of there's no initializer"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.name._walk(visitor);
|
||||
if (this.value) this.value._walk(visitor);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/* -----[ OTHER ]----- */
|
||||
|
||||
var AST_Call = DEFNODE("Call", "expression args", {
|
||||
$documentation: "A function call expression",
|
||||
$propdoc: {
|
||||
expression: "[AST_Node] expression to invoke as function",
|
||||
args: "[AST_Node*] array of arguments"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.expression._walk(visitor);
|
||||
this.args.forEach(function(arg){
|
||||
arg._walk(visitor);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
var AST_New = DEFNODE("New", null, {
|
||||
$documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
|
||||
}, AST_Call);
|
||||
|
||||
var AST_Seq = DEFNODE("Seq", "car cdr", {
|
||||
$documentation: "A sequence expression (two comma-separated expressions)",
|
||||
$propdoc: {
|
||||
car: "[AST_Node] first element in sequence",
|
||||
cdr: "[AST_Node] second element in sequence"
|
||||
},
|
||||
$cons: function(x, y) {
|
||||
var seq = new AST_Seq(x);
|
||||
seq.car = x;
|
||||
seq.cdr = y;
|
||||
return seq;
|
||||
},
|
||||
$from_array: function(array) {
|
||||
if (array.length == 0) return null;
|
||||
if (array.length == 1) return array[0].clone();
|
||||
var list = null;
|
||||
for (var i = array.length; --i >= 0;) {
|
||||
list = AST_Seq.cons(array[i], list);
|
||||
}
|
||||
var p = list;
|
||||
while (p) {
|
||||
if (p.cdr && !p.cdr.cdr) {
|
||||
p.cdr = p.cdr.car;
|
||||
break;
|
||||
}
|
||||
p = p.cdr;
|
||||
}
|
||||
return list;
|
||||
},
|
||||
to_array: function() {
|
||||
var p = this, a = [];
|
||||
while (p) {
|
||||
a.push(p.car);
|
||||
if (p.cdr && !(p.cdr instanceof AST_Seq)) {
|
||||
a.push(p.cdr);
|
||||
break;
|
||||
}
|
||||
p = p.cdr;
|
||||
}
|
||||
return a;
|
||||
},
|
||||
add: function(node) {
|
||||
var p = this;
|
||||
while (p) {
|
||||
if (!(p.cdr instanceof AST_Seq)) {
|
||||
var cell = AST_Seq.cons(p.cdr, node);
|
||||
return p.cdr = cell;
|
||||
}
|
||||
p = p.cdr;
|
||||
}
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.car._walk(visitor);
|
||||
if (this.cdr) this.cdr._walk(visitor);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
|
||||
$documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
|
||||
$propdoc: {
|
||||
expression: "[AST_Node] the “container” expression",
|
||||
property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node"
|
||||
}
|
||||
});
|
||||
|
||||
var AST_Dot = DEFNODE("Dot", null, {
|
||||
$documentation: "A dotted property access expression",
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.expression._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_PropAccess);
|
||||
|
||||
var AST_Sub = DEFNODE("Sub", null, {
|
||||
$documentation: "Index-style property access, i.e. `a[\"foo\"]`",
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.expression._walk(visitor);
|
||||
this.property._walk(visitor);
|
||||
});
|
||||
}
|
||||
}, AST_PropAccess);
|
||||
|
||||
var AST_Unary = DEFNODE("Unary", "operator expression", {
|
||||
$documentation: "Base class for unary expressions",
|
||||
$propdoc: {
|
||||
operator: "[string] the operator",
|
||||
expression: "[AST_Node] expression that this unary operator applies to"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.expression._walk(visitor);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
|
||||
$documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
|
||||
}, AST_Unary);
|
||||
|
||||
var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
|
||||
$documentation: "Unary postfix expression, i.e. `i++`"
|
||||
}, AST_Unary);
|
||||
|
||||
var AST_Binary = DEFNODE("Binary", "left operator right", {
|
||||
$documentation: "Binary expression, i.e. `a + b`",
|
||||
$propdoc: {
|
||||
left: "[AST_Node] left-hand side expression",
|
||||
operator: "[string] the operator",
|
||||
right: "[AST_Node] right-hand side expression"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.left._walk(visitor);
|
||||
this.right._walk(visitor);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
|
||||
$documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
|
||||
$propdoc: {
|
||||
condition: "[AST_Node]",
|
||||
consequent: "[AST_Node]",
|
||||
alternative: "[AST_Node]"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.condition._walk(visitor);
|
||||
this.consequent._walk(visitor);
|
||||
this.alternative._walk(visitor);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
var AST_Assign = DEFNODE("Assign", null, {
|
||||
$documentation: "An assignment expression — `a = b + 5`",
|
||||
}, AST_Binary);
|
||||
|
||||
/* -----[ LITERALS ]----- */
|
||||
|
||||
var AST_Array = DEFNODE("Array", "elements", {
|
||||
$documentation: "An array literal",
|
||||
$propdoc: {
|
||||
elements: "[AST_Node*] array of elements"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.elements.forEach(function(el){
|
||||
el._walk(visitor);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
var AST_Object = DEFNODE("Object", "properties", {
|
||||
$documentation: "An object literal",
|
||||
$propdoc: {
|
||||
properties: "[AST_ObjectProperty*] array of properties"
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.properties.forEach(function(prop){
|
||||
prop._walk(visitor);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
|
||||
$documentation: "Base class for literal object properties",
|
||||
$propdoc: {
|
||||
key: "[string] the property name; it's always a plain string in our AST, no matter if it was a string, number or identifier in original code",
|
||||
value: "[AST_Node] property value. For setters and getters this is an AST_Function."
|
||||
},
|
||||
_walk: function(visitor) {
|
||||
return visitor._visit(this, function(){
|
||||
this.value._walk(visitor);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, {
|
||||
$documentation: "A key: value object property",
|
||||
}, AST_ObjectProperty);
|
||||
|
||||
var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
|
||||
$documentation: "An object setter property",
|
||||
}, AST_ObjectProperty);
|
||||
|
||||
var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
|
||||
$documentation: "An object getter property",
|
||||
}, AST_ObjectProperty);
|
||||
|
||||
var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
|
||||
$propdoc: {
|
||||
name: "[string] name of this symbol",
|
||||
scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
|
||||
thedef: "[SymbolDef/S] the definition of this symbol"
|
||||
},
|
||||
$documentation: "Base class for all symbols",
|
||||
});
|
||||
|
||||
var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
|
||||
$documentation: "The name of a property accessor (setter/getter function)"
|
||||
}, AST_Symbol);
|
||||
|
||||
var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
|
||||
$documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",
|
||||
$propdoc: {
|
||||
init: "[AST_Node*/S] array of initializers for this declaration."
|
||||
}
|
||||
}, AST_Symbol);
|
||||
|
||||
var AST_SymbolVar = DEFNODE("SymbolVar", null, {
|
||||
$documentation: "Symbol defining a variable",
|
||||
}, AST_SymbolDeclaration);
|
||||
|
||||
var AST_SymbolConst = DEFNODE("SymbolConst", null, {
|
||||
$documentation: "A constant declaration"
|
||||
}, AST_SymbolDeclaration);
|
||||
|
||||
var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
|
||||
$documentation: "Symbol naming a function argument",
|
||||
}, AST_SymbolVar);
|
||||
|
||||
var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
|
||||
$documentation: "Symbol defining a function",
|
||||
}, AST_SymbolDeclaration);
|
||||
|
||||
var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
|
||||
$documentation: "Symbol naming a function expression",
|
||||
}, AST_SymbolDeclaration);
|
||||
|
||||
var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
|
||||
$documentation: "Symbol naming the exception in catch",
|
||||
}, AST_SymbolDeclaration);
|
||||
|
||||
var AST_Label = DEFNODE("Label", "references", {
|
||||
$documentation: "Symbol naming a label (declaration)",
|
||||
$propdoc: {
|
||||
references: "[AST_LabelRef*] a list of nodes referring to this label"
|
||||
}
|
||||
}, AST_Symbol);
|
||||
|
||||
var AST_SymbolRef = DEFNODE("SymbolRef", null, {
|
||||
$documentation: "Reference to some symbol (not definition/declaration)",
|
||||
}, AST_Symbol);
|
||||
|
||||
var AST_LabelRef = DEFNODE("LabelRef", null, {
|
||||
$documentation: "Reference to a label symbol",
|
||||
}, AST_Symbol);
|
||||
|
||||
var AST_This = DEFNODE("This", null, {
|
||||
$documentation: "The `this` symbol",
|
||||
}, AST_Symbol);
|
||||
|
||||
var AST_Constant = DEFNODE("Constant", null, {
|
||||
$documentation: "Base class for all constants",
|
||||
getValue: function() {
|
||||
return this.value;
|
||||
}
|
||||
});
|
||||
|
||||
var AST_String = DEFNODE("String", "value", {
|
||||
$documentation: "A string literal",
|
||||
$propdoc: {
|
||||
value: "[string] the contents of this string"
|
||||
}
|
||||
}, AST_Constant);
|
||||
|
||||
var AST_Number = DEFNODE("Number", "value", {
|
||||
$documentation: "A number literal",
|
||||
$propdoc: {
|
||||
value: "[number] the numeric value"
|
||||
}
|
||||
}, AST_Constant);
|
||||
|
||||
var AST_RegExp = DEFNODE("RegExp", "value", {
|
||||
$documentation: "A regexp literal",
|
||||
$propdoc: {
|
||||
value: "[RegExp] the actual regexp"
|
||||
}
|
||||
}, AST_Constant);
|
||||
|
||||
var AST_Atom = DEFNODE("Atom", null, {
|
||||
$documentation: "Base class for atoms",
|
||||
}, AST_Constant);
|
||||
|
||||
var AST_Null = DEFNODE("Null", null, {
|
||||
$documentation: "The `null` atom",
|
||||
value: null
|
||||
}, AST_Atom);
|
||||
|
||||
var AST_NaN = DEFNODE("NaN", null, {
|
||||
$documentation: "The impossible value",
|
||||
value: 0/0
|
||||
}, AST_Atom);
|
||||
|
||||
var AST_Undefined = DEFNODE("Undefined", null, {
|
||||
$documentation: "The `undefined` value",
|
||||
value: (function(){}())
|
||||
}, AST_Atom);
|
||||
|
||||
var AST_Hole = DEFNODE("Hole", null, {
|
||||
$documentation: "A hole in an array",
|
||||
value: (function(){}())
|
||||
}, AST_Atom);
|
||||
|
||||
var AST_Infinity = DEFNODE("Infinity", null, {
|
||||
$documentation: "The `Infinity` value",
|
||||
value: 1/0
|
||||
}, AST_Atom);
|
||||
|
||||
var AST_Boolean = DEFNODE("Boolean", null, {
|
||||
$documentation: "Base class for booleans",
|
||||
}, AST_Atom);
|
||||
|
||||
var AST_False = DEFNODE("False", null, {
|
||||
$documentation: "The `false` atom",
|
||||
value: false
|
||||
}, AST_Boolean);
|
||||
|
||||
var AST_True = DEFNODE("True", null, {
|
||||
$documentation: "The `true` atom",
|
||||
value: true
|
||||
}, AST_Boolean);
|
||||
|
||||
/* -----[ TreeWalker ]----- */
|
||||
|
||||
function TreeWalker(callback) {
|
||||
this.visit = callback;
|
||||
this.stack = [];
|
||||
};
|
||||
TreeWalker.prototype = {
|
||||
_visit: function(node, descend) {
|
||||
this.stack.push(node);
|
||||
var ret = this.visit(node, descend ? function(){
|
||||
descend.call(node);
|
||||
} : noop);
|
||||
if (!ret && descend) {
|
||||
descend.call(node);
|
||||
}
|
||||
this.stack.pop();
|
||||
return ret;
|
||||
},
|
||||
parent: function(n) {
|
||||
return this.stack[this.stack.length - 2 - (n || 0)];
|
||||
},
|
||||
push: function (node) {
|
||||
this.stack.push(node);
|
||||
},
|
||||
pop: function() {
|
||||
return this.stack.pop();
|
||||
},
|
||||
self: function() {
|
||||
return this.stack[this.stack.length - 1];
|
||||
},
|
||||
find_parent: function(type) {
|
||||
var stack = this.stack;
|
||||
for (var i = stack.length; --i >= 0;) {
|
||||
var x = stack[i];
|
||||
if (x instanceof type) return x;
|
||||
}
|
||||
},
|
||||
in_boolean_context: function() {
|
||||
var stack = this.stack;
|
||||
var i = stack.length, self = stack[--i];
|
||||
while (i > 0) {
|
||||
var p = stack[--i];
|
||||
if ((p instanceof AST_If && p.condition === self) ||
|
||||
(p instanceof AST_Conditional && p.condition === self) ||
|
||||
(p instanceof AST_DWLoop && p.condition === self) ||
|
||||
(p instanceof AST_For && p.condition === self) ||
|
||||
(p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")))
|
||||
return false;
|
||||
self = p;
|
||||
}
|
||||
},
|
||||
loopcontrol_target: function(label) {
|
||||
var stack = this.stack;
|
||||
if (label) {
|
||||
for (var i = stack.length; --i >= 0;) {
|
||||
var x = stack[i];
|
||||
if (x instanceof AST_LabeledStatement && x.label.name == label.name) {
|
||||
return x.body;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (var i = stack.length; --i >= 0;) {
|
||||
var x = stack[i];
|
||||
if (x instanceof AST_Switch
|
||||
|| x instanceof AST_For
|
||||
|| x instanceof AST_ForIn
|
||||
|| x instanceof AST_DWLoop) return x;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
File diff suppressed because it is too large
Load Diff
|
@ -1,265 +0,0 @@
|
|||
/***********************************************************************
|
||||
|
||||
A JavaScript tokenizer / parser / beautifier / compressor.
|
||||
https://github.com/mishoo/UglifyJS2
|
||||
|
||||
-------------------------------- (C) ---------------------------------
|
||||
|
||||
Author: Mihai Bazon
|
||||
<mihai.bazon@gmail.com>
|
||||
http://mihai.bazon.net/blog
|
||||
|
||||
Distributed under the BSD license:
|
||||
|
||||
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
* Redistributions of source code must retain the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials
|
||||
provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
|
||||
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
||||
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
|
||||
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGE.
|
||||
|
||||
***********************************************************************/
|
||||
|
||||
"use strict";
|
||||
|
||||
(function(){
|
||||
|
||||
var MOZ_TO_ME = {
|
||||
TryStatement : function(M) {
|
||||
return new AST_Try({
|
||||
start : my_start_token(M),
|
||||
end : my_end_token(M),
|
||||
body : from_moz(M.block).body,
|
||||
bcatch : from_moz(M.handlers[0]),
|
||||
bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
|
||||
});
|
||||
},
|
||||
CatchClause : function(M) {
|
||||
return new AST_Catch({
|
||||
start : my_start_token(M),
|
||||
end : my_end_token(M),
|
||||
argname : from_moz(M.param),
|
||||
body : from_moz(M.body).body
|
||||
});
|
||||
},
|
||||
ObjectExpression : function(M) {
|
||||
return new AST_Object({
|
||||
start : my_start_token(M),
|
||||
end : my_end_token(M),
|
||||
properties : M.properties.map(function(prop){
|
||||
var key = prop.key;
|
||||
var name = key.type == "Identifier" ? key.name : key.value;
|
||||
var args = {
|
||||
start : my_start_token(key),
|
||||
end : my_end_token(prop.value),
|
||||
key : name,
|
||||
value : from_moz(prop.value)
|
||||
};
|
||||
switch (prop.kind) {
|
||||
case "init":
|
||||
return new AST_ObjectKeyVal(args);
|
||||
case "set":
|
||||
args.value.name = from_moz(key);
|
||||
return new AST_ObjectSetter(args);
|
||||
case "get":
|
||||
args.value.name = from_moz(key);
|
||||
return new AST_ObjectGetter(args);
|
||||
}
|
||||
})
|
||||
});
|
||||
},
|
||||
SequenceExpression : function(M) {
|
||||
return AST_Seq.from_array(M.expressions.map(from_moz));
|
||||
},
|
||||
MemberExpression : function(M) {
|
||||
return new (M.computed ? AST_Sub : AST_Dot)({
|
||||
start : my_start_token(M),
|
||||
end : my_end_token(M),
|
||||
property : M.computed ? from_moz(M.property) : M.property.name,
|
||||
expression : from_moz(M.object)
|
||||
});
|
||||
},
|
||||
SwitchCase : function(M) {
|
||||
return new (M.test ? AST_Case : AST_Default)({
|
||||
start : my_start_token(M),
|
||||
end : my_end_token(M),
|
||||
expression : from_moz(M.test),
|
||||
body : M.consequent.map(from_moz)
|
||||
});
|
||||
},
|
||||
Literal : function(M) {
|
||||
var val = M.value, args = {
|
||||
start : my_start_token(M),
|
||||
end : my_end_token(M)
|
||||
};
|
||||
if (val === null) return new AST_Null(args);
|
||||
switch (typeof val) {
|
||||
case "string":
|
||||
args.value = val;
|
||||
return new AST_String(args);
|
||||
case "number":
|
||||
args.value = val;
|
||||
return new AST_Number(args);
|
||||
case "boolean":
|
||||
return new (val ? AST_True : AST_False)(args);
|
||||
default:
|
||||
args.value = val;
|
||||
return new AST_RegExp(args);
|
||||
}
|
||||
},
|
||||
UnaryExpression: From_Moz_Unary,
|
||||
UpdateExpression: From_Moz_Unary,
|
||||
Identifier: function(M) {
|
||||
var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
|
||||
return new (M.name == "this" ? AST_This
|
||||
: p.type == "LabeledStatement" ? AST_Label
|
||||
: p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar)
|
||||
: p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
|
||||
: p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
|
||||
: p.type == "CatchClause" ? AST_SymbolCatch
|
||||
: p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
|
||||
: AST_SymbolRef)({
|
||||
start : my_start_token(M),
|
||||
end : my_end_token(M),
|
||||
name : M.name
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
function From_Moz_Unary(M) {
|
||||
return new (M.prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
|
||||
start : my_start_token(M),
|
||||
end : my_end_token(M),
|
||||
operator : M.operator,
|
||||
expression : from_moz(M.argument)
|
||||
})
|
||||
};
|
||||
|
||||
var ME_TO_MOZ = {};
|
||||
|
||||
map("Node", AST_Node);
|
||||
map("Program", AST_Toplevel, "body@body");
|
||||
map("Function", AST_Function, "id>name, params@argnames, body%body");
|
||||
map("EmptyStatement", AST_EmptyStatement);
|
||||
map("BlockStatement", AST_BlockStatement, "body@body");
|
||||
map("ExpressionStatement", AST_SimpleStatement, "expression>body");
|
||||
map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
|
||||
map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
|
||||
map("BreakStatement", AST_Break, "label>label");
|
||||
map("ContinueStatement", AST_Continue, "label>label");
|
||||
map("WithStatement", AST_With, "object>expression, body>body");
|
||||
map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
|
||||
map("ReturnStatement", AST_Return, "argument>value");
|
||||
map("ThrowStatement", AST_Throw, "argument>value");
|
||||
map("WhileStatement", AST_While, "test>condition, body>body");
|
||||
map("DoWhileStatement", AST_Do, "test>condition, body>body");
|
||||
map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
|
||||
map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
|
||||
map("DebuggerStatement", AST_Debugger);
|
||||
map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body");
|
||||
map("VariableDeclaration", AST_Var, "declarations@definitions");
|
||||
map("VariableDeclarator", AST_VarDef, "id>name, init>value");
|
||||
|
||||
map("ThisExpression", AST_This);
|
||||
map("ArrayExpression", AST_Array, "elements@elements");
|
||||
map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body");
|
||||
map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
|
||||
map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
|
||||
map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
|
||||
map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
|
||||
map("NewExpression", AST_New, "callee>expression, arguments@args");
|
||||
map("CallExpression", AST_Call, "callee>expression, arguments@args");
|
||||
|
||||
/* -----[ tools ]----- */
|
||||
|
||||
function my_start_token(moznode) {
|
||||
return new AST_Token({
|
||||
file : moznode.loc && moznode.loc.source,
|
||||
line : moznode.loc && moznode.loc.start.line,
|
||||
col : moznode.loc && moznode.loc.start.column,
|
||||
pos : moznode.start,
|
||||
endpos : moznode.start
|
||||
});
|
||||
};
|
||||
|
||||
function my_end_token(moznode) {
|
||||
return new AST_Token({
|
||||
file : moznode.loc && moznode.loc.source,
|
||||
line : moznode.loc && moznode.loc.end.line,
|
||||
col : moznode.loc && moznode.loc.end.column,
|
||||
pos : moznode.end,
|
||||
endpos : moznode.end
|
||||
});
|
||||
};
|
||||
|
||||
function map(moztype, mytype, propmap) {
|
||||
var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
|
||||
moz_to_me += "return new mytype({\n" +
|
||||
"start: my_start_token(M),\n" +
|
||||
"end: my_end_token(M)";
|
||||
|
||||
if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){
|
||||
var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
|
||||
if (!m) throw new Error("Can't understand property map: " + prop);
|
||||
var moz = "M." + m[1], how = m[2], my = m[3];
|
||||
moz_to_me += ",\n" + my + ": ";
|
||||
if (how == "@") {
|
||||
moz_to_me += moz + ".map(from_moz)";
|
||||
} else if (how == ">") {
|
||||
moz_to_me += "from_moz(" + moz + ")";
|
||||
} else if (how == "=") {
|
||||
moz_to_me += moz;
|
||||
} else if (how == "%") {
|
||||
moz_to_me += "from_moz(" + moz + ").body";
|
||||
} else throw new Error("Can't understand operator in propmap: " + prop);
|
||||
});
|
||||
moz_to_me += "\n})}";
|
||||
|
||||
// moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
|
||||
// console.log(moz_to_me);
|
||||
|
||||
moz_to_me = new Function("mytype", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
|
||||
mytype, my_start_token, my_end_token, from_moz
|
||||
);
|
||||
return MOZ_TO_ME[moztype] = moz_to_me;
|
||||
};
|
||||
|
||||
var FROM_MOZ_STACK = null;
|
||||
|
||||
function from_moz(node) {
|
||||
FROM_MOZ_STACK.push(node);
|
||||
var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
|
||||
FROM_MOZ_STACK.pop();
|
||||
return ret;
|
||||
};
|
||||
|
||||
AST_Node.from_mozilla_ast = function(node){
|
||||
var save_stack = FROM_MOZ_STACK;
|
||||
FROM_MOZ_STACK = [];
|
||||
var ast = from_moz(node);
|
||||
FROM_MOZ_STACK = save_stack;
|
||||
return ast;
|
||||
};
|
||||
|
||||
})();
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -1,580 +0,0 @@
|
|||
/***********************************************************************
|
||||
|
||||
A JavaScript tokenizer / parser / beautifier / compressor.
|
||||
https://github.com/mishoo/UglifyJS2
|
||||
|
||||
-------------------------------- (C) ---------------------------------
|
||||
|
||||
Author: Mihai Bazon
|
||||
<mihai.bazon@gmail.com>
|
||||
http://mihai.bazon.net/blog
|
||||
|
||||
Distributed under the BSD license:
|
||||
|
||||
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
* Redistributions of source code must retain the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials
|
||||
provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
|
||||
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
||||
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
|
||||
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGE.
|
||||
|
||||
***********************************************************************/
|
||||
|
||||
"use strict";
|
||||
|
||||
function SymbolDef(scope, index, orig) {
|
||||
this.name = orig.name;
|
||||
this.orig = [ orig ];
|
||||
this.scope = scope;
|
||||
this.references = [];
|
||||
this.global = false;
|
||||
this.mangled_name = null;
|
||||
this.undeclared = false;
|
||||
this.constant = false;
|
||||
this.index = index;
|
||||
};
|
||||
|
||||
SymbolDef.prototype = {
|
||||
unmangleable: function(options) {
|
||||
return this.global
|
||||
|| this.undeclared
|
||||
|| (!(options && options.eval) && (this.scope.uses_eval || this.scope.uses_with));
|
||||
},
|
||||
mangle: function(options) {
|
||||
if (!this.mangled_name && !this.unmangleable(options))
|
||||
this.mangled_name = this.scope.next_mangled(options);
|
||||
}
|
||||
};
|
||||
|
||||
AST_Toplevel.DEFMETHOD("figure_out_scope", function(){
|
||||
// This does what ast_add_scope did in UglifyJS v1.
|
||||
//
|
||||
// Part of it could be done at parse time, but it would complicate
|
||||
// the parser (and it's already kinda complex). It's also worth
|
||||
// having it separated because we might need to call it multiple
|
||||
// times on the same tree.
|
||||
|
||||
// pass 1: setup scope chaining and handle definitions
|
||||
var self = this;
|
||||
var scope = self.parent_scope = null;
|
||||
var labels = new Dictionary();
|
||||
var nesting = 0;
|
||||
var tw = new TreeWalker(function(node, descend){
|
||||
if (node instanceof AST_Scope) {
|
||||
node.init_scope_vars(nesting);
|
||||
var save_scope = node.parent_scope = scope;
|
||||
var save_labels = labels;
|
||||
++nesting;
|
||||
scope = node;
|
||||
labels = new Dictionary();
|
||||
descend();
|
||||
labels = save_labels;
|
||||
scope = save_scope;
|
||||
--nesting;
|
||||
return true; // don't descend again in TreeWalker
|
||||
}
|
||||
if (node instanceof AST_Directive) {
|
||||
node.scope = scope;
|
||||
push_uniq(scope.directives, node.value);
|
||||
return true;
|
||||
}
|
||||
if (node instanceof AST_With) {
|
||||
for (var s = scope; s; s = s.parent_scope)
|
||||
s.uses_with = true;
|
||||
return;
|
||||
}
|
||||
if (node instanceof AST_LabeledStatement) {
|
||||
var l = node.label;
|
||||
if (labels.has(l.name))
|
||||
throw new Error(string_template("Label {name} defined twice", l));
|
||||
labels.set(l.name, l);
|
||||
descend();
|
||||
labels.del(l.name);
|
||||
return true; // no descend again
|
||||
}
|
||||
if (node instanceof AST_Symbol) {
|
||||
node.scope = scope;
|
||||
}
|
||||
if (node instanceof AST_Label) {
|
||||
node.thedef = node;
|
||||
node.init_scope_vars();
|
||||
}
|
||||
if (node instanceof AST_SymbolLambda) {
|
||||
//scope.def_function(node);
|
||||
//
|
||||
// https://github.com/mishoo/UglifyJS2/issues/24 — MSIE
|
||||
// leaks function expression names into the containing
|
||||
// scope. Don't like this fix but seems we can't do any
|
||||
// better. IE: please die. Please!
|
||||
(node.scope = scope.parent_scope).def_function(node);
|
||||
}
|
||||
else if (node instanceof AST_SymbolDefun) {
|
||||
// Careful here, the scope where this should be defined is
|
||||
// the parent scope. The reason is that we enter a new
|
||||
// scope when we encounter the AST_Defun node (which is
|
||||
// instanceof AST_Scope) but we get to the symbol a bit
|
||||
// later.
|
||||
(node.scope = scope.parent_scope).def_function(node);
|
||||
}
|
||||
else if (node instanceof AST_SymbolVar
|
||||
|| node instanceof AST_SymbolConst) {
|
||||
var def = scope.def_variable(node);
|
||||
def.constant = node instanceof AST_SymbolConst;
|
||||
def.init = tw.parent().value;
|
||||
}
|
||||
else if (node instanceof AST_SymbolCatch) {
|
||||
// XXX: this is wrong according to ECMA-262 (12.4). the
|
||||
// `catch` argument name should be visible only inside the
|
||||
// catch block. For a quick fix AST_Catch should inherit
|
||||
// from AST_Scope. Keeping it this way because of IE,
|
||||
// which doesn't obey the standard. (it introduces the
|
||||
// identifier in the enclosing scope)
|
||||
scope.def_variable(node);
|
||||
}
|
||||
if (node instanceof AST_LabelRef) {
|
||||
var sym = labels.get(node.name);
|
||||
if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {
|
||||
name: node.name,
|
||||
line: node.start.line,
|
||||
col: node.start.col
|
||||
}));
|
||||
node.thedef = sym;
|
||||
}
|
||||
});
|
||||
self.walk(tw);
|
||||
|
||||
// pass 2: find back references and eval
|
||||
var func = null;
|
||||
var globals = self.globals = new Dictionary();
|
||||
var tw = new TreeWalker(function(node, descend){
|
||||
if (node instanceof AST_Lambda) {
|
||||
var prev_func = func;
|
||||
func = node;
|
||||
descend();
|
||||
func = prev_func;
|
||||
return true;
|
||||
}
|
||||
if (node instanceof AST_LabelRef) {
|
||||
node.reference();
|
||||
return true;
|
||||
}
|
||||
if (node instanceof AST_SymbolRef) {
|
||||
var name = node.name;
|
||||
var sym = node.scope.find_variable(name);
|
||||
if (!sym) {
|
||||
var g;
|
||||
if (globals.has(name)) {
|
||||
g = globals.get(name);
|
||||
} else {
|
||||
g = new SymbolDef(self, globals.size(), node);
|
||||
g.undeclared = true;
|
||||
globals.set(name, g);
|
||||
}
|
||||
node.thedef = g;
|
||||
if (name == "eval" && tw.parent() instanceof AST_Call) {
|
||||
for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope)
|
||||
s.uses_eval = true;
|
||||
}
|
||||
if (name == "arguments") {
|
||||
func.uses_arguments = true;
|
||||
}
|
||||
} else {
|
||||
node.thedef = sym;
|
||||
}
|
||||
node.reference();
|
||||
return true;
|
||||
}
|
||||
});
|
||||
self.walk(tw);
|
||||
});
|
||||
|
||||
AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){
|
||||
this.directives = []; // contains the directives defined in this scope, i.e. "use strict"
|
||||
this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
|
||||
this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
|
||||
this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
|
||||
this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
|
||||
this.parent_scope = null; // the parent scope
|
||||
this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
|
||||
this.cname = -1; // the current index for mangling functions/variables
|
||||
this.nesting = nesting; // the nesting level of this scope (0 means toplevel)
|
||||
});
|
||||
|
||||
AST_Scope.DEFMETHOD("strict", function(){
|
||||
return this.has_directive("use strict");
|
||||
});
|
||||
|
||||
AST_Lambda.DEFMETHOD("init_scope_vars", function(){
|
||||
AST_Scope.prototype.init_scope_vars.apply(this, arguments);
|
||||
this.uses_arguments = false;
|
||||
});
|
||||
|
||||
AST_SymbolRef.DEFMETHOD("reference", function() {
|
||||
var def = this.definition();
|
||||
def.references.push(this);
|
||||
var s = this.scope;
|
||||
while (s) {
|
||||
push_uniq(s.enclosed, def);
|
||||
if (s === def.scope) break;
|
||||
s = s.parent_scope;
|
||||
}
|
||||
this.frame = this.scope.nesting - def.scope.nesting;
|
||||
});
|
||||
|
||||
AST_Label.DEFMETHOD("init_scope_vars", function(){
|
||||
this.references = [];
|
||||
});
|
||||
|
||||
AST_LabelRef.DEFMETHOD("reference", function(){
|
||||
this.thedef.references.push(this);
|
||||
});
|
||||
|
||||
AST_Scope.DEFMETHOD("find_variable", function(name){
|
||||
if (name instanceof AST_Symbol) name = name.name;
|
||||
return this.variables.get(name)
|
||||
|| (this.parent_scope && this.parent_scope.find_variable(name));
|
||||
});
|
||||
|
||||
AST_Scope.DEFMETHOD("has_directive", function(value){
|
||||
return this.parent_scope && this.parent_scope.has_directive(value)
|
||||
|| (this.directives.indexOf(value) >= 0 ? this : null);
|
||||
});
|
||||
|
||||
AST_Scope.DEFMETHOD("def_function", function(symbol){
|
||||
this.functions.set(symbol.name, this.def_variable(symbol));
|
||||
});
|
||||
|
||||
AST_Scope.DEFMETHOD("def_variable", function(symbol){
|
||||
var def;
|
||||
if (!this.variables.has(symbol.name)) {
|
||||
def = new SymbolDef(this, this.variables.size(), symbol);
|
||||
this.variables.set(symbol.name, def);
|
||||
def.global = !this.parent_scope;
|
||||
} else {
|
||||
def = this.variables.get(symbol.name);
|
||||
def.orig.push(symbol);
|
||||
}
|
||||
return symbol.thedef = def;
|
||||
});
|
||||
|
||||
AST_Scope.DEFMETHOD("next_mangled", function(options){
|
||||
var ext = this.enclosed, n = ext.length;
|
||||
out: while (true) {
|
||||
var m = base54(++this.cname);
|
||||
if (!is_identifier(m)) continue; // skip over "do"
|
||||
// we must ensure that the mangled name does not shadow a name
|
||||
// from some parent scope that is referenced in this or in
|
||||
// inner scopes.
|
||||
for (var i = n; --i >= 0;) {
|
||||
var sym = ext[i];
|
||||
var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);
|
||||
if (m == name) continue out;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
});
|
||||
|
||||
AST_Scope.DEFMETHOD("references", function(sym){
|
||||
if (sym instanceof AST_Symbol) sym = sym.definition();
|
||||
return this.enclosed.indexOf(sym) < 0 ? null : sym;
|
||||
});
|
||||
|
||||
AST_Symbol.DEFMETHOD("unmangleable", function(options){
|
||||
return this.definition().unmangleable(options);
|
||||
});
|
||||
|
||||
// property accessors are not mangleable
|
||||
AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){
|
||||
return true;
|
||||
});
|
||||
|
||||
// labels are always mangleable
|
||||
AST_Label.DEFMETHOD("unmangleable", function(){
|
||||
return false;
|
||||
});
|
||||
|
||||
AST_Symbol.DEFMETHOD("unreferenced", function(){
|
||||
return this.definition().references.length == 0
|
||||
&& !(this.scope.uses_eval || this.scope.uses_with);
|
||||
});
|
||||
|
||||
AST_Symbol.DEFMETHOD("undeclared", function(){
|
||||
return this.definition().undeclared;
|
||||
});
|
||||
|
||||
AST_LabelRef.DEFMETHOD("undeclared", function(){
|
||||
return false;
|
||||
});
|
||||
|
||||
AST_Label.DEFMETHOD("undeclared", function(){
|
||||
return false;
|
||||
});
|
||||
|
||||
AST_Symbol.DEFMETHOD("definition", function(){
|
||||
return this.thedef;
|
||||
});
|
||||
|
||||
AST_Symbol.DEFMETHOD("global", function(){
|
||||
return this.definition().global;
|
||||
});
|
||||
|
||||
AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){
|
||||
return defaults(options, {
|
||||
except : [],
|
||||
eval : false,
|
||||
sort : false
|
||||
});
|
||||
});
|
||||
|
||||
AST_Toplevel.DEFMETHOD("mangle_names", function(options){
|
||||
options = this._default_mangler_options(options);
|
||||
// We only need to mangle declaration nodes. Special logic wired
|
||||
// into the code generator will display the mangled name if it's
|
||||
// present (and for AST_SymbolRef-s it'll use the mangled name of
|
||||
// the AST_SymbolDeclaration that it points to).
|
||||
var lname = -1;
|
||||
var to_mangle = [];
|
||||
var tw = new TreeWalker(function(node, descend){
|
||||
if (node instanceof AST_LabeledStatement) {
|
||||
// lname is incremented when we get to the AST_Label
|
||||
var save_nesting = lname;
|
||||
descend();
|
||||
lname = save_nesting;
|
||||
return true; // don't descend again in TreeWalker
|
||||
}
|
||||
if (node instanceof AST_Scope) {
|
||||
var p = tw.parent(), a = [];
|
||||
node.variables.each(function(symbol){
|
||||
if (options.except.indexOf(symbol.name) < 0) {
|
||||
a.push(symbol);
|
||||
}
|
||||
});
|
||||
if (options.sort) a.sort(function(a, b){
|
||||
return b.references.length - a.references.length;
|
||||
});
|
||||
to_mangle.push.apply(to_mangle, a);
|
||||
return;
|
||||
}
|
||||
if (node instanceof AST_Label) {
|
||||
var name;
|
||||
do name = base54(++lname); while (!is_identifier(name));
|
||||
node.mangled_name = name;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
this.walk(tw);
|
||||
to_mangle.forEach(function(def){ def.mangle(options) });
|
||||
});
|
||||
|
||||
AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){
|
||||
options = this._default_mangler_options(options);
|
||||
var tw = new TreeWalker(function(node){
|
||||
if (node instanceof AST_Constant)
|
||||
base54.consider(node.print_to_string());
|
||||
else if (node instanceof AST_Return)
|
||||
base54.consider("return");
|
||||
else if (node instanceof AST_Throw)
|
||||
base54.consider("throw");
|
||||
else if (node instanceof AST_Continue)
|
||||
base54.consider("continue");
|
||||
else if (node instanceof AST_Break)
|
||||
base54.consider("break");
|
||||
else if (node instanceof AST_Debugger)
|
||||
base54.consider("debugger");
|
||||
else if (node instanceof AST_Directive)
|
||||
base54.consider(node.value);
|
||||
else if (node instanceof AST_While)
|
||||
base54.consider("while");
|
||||
else if (node instanceof AST_Do)
|
||||
base54.consider("do while");
|
||||
else if (node instanceof AST_If) {
|
||||
base54.consider("if");
|
||||
if (node.alternative) base54.consider("else");
|
||||
}
|
||||
else if (node instanceof AST_Var)
|
||||
base54.consider("var");
|
||||
else if (node instanceof AST_Const)
|
||||
base54.consider("const");
|
||||
else if (node instanceof AST_Lambda)
|
||||
base54.consider("function");
|
||||
else if (node instanceof AST_For)
|
||||
base54.consider("for");
|
||||
else if (node instanceof AST_ForIn)
|
||||
base54.consider("for in");
|
||||
else if (node instanceof AST_Switch)
|
||||
base54.consider("switch");
|
||||
else if (node instanceof AST_Case)
|
||||
base54.consider("case");
|
||||
else if (node instanceof AST_Default)
|
||||
base54.consider("default");
|
||||
else if (node instanceof AST_With)
|
||||
base54.consider("with");
|
||||
else if (node instanceof AST_ObjectSetter)
|
||||
base54.consider("set" + node.key);
|
||||
else if (node instanceof AST_ObjectGetter)
|
||||
base54.consider("get" + node.key);
|
||||
else if (node instanceof AST_ObjectKeyVal)
|
||||
base54.consider(node.key);
|
||||
else if (node instanceof AST_New)
|
||||
base54.consider("new");
|
||||
else if (node instanceof AST_This)
|
||||
base54.consider("this");
|
||||
else if (node instanceof AST_Try)
|
||||
base54.consider("try");
|
||||
else if (node instanceof AST_Catch)
|
||||
base54.consider("catch");
|
||||
else if (node instanceof AST_Finally)
|
||||
base54.consider("finally");
|
||||
else if (node instanceof AST_Symbol && node.unmangleable(options))
|
||||
base54.consider(node.name);
|
||||
else if (node instanceof AST_Unary || node instanceof AST_Binary)
|
||||
base54.consider(node.operator);
|
||||
else if (node instanceof AST_Dot)
|
||||
base54.consider(node.property);
|
||||
});
|
||||
this.walk(tw);
|
||||
base54.sort();
|
||||
});
|
||||
|
||||
var base54 = (function() {
|
||||
var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
|
||||
var chars, frequency;
|
||||
function reset() {
|
||||
frequency = Object.create(null);
|
||||
chars = string.split("").map(function(ch){ return ch.charCodeAt(0) });
|
||||
chars.forEach(function(ch){ frequency[ch] = 0 });
|
||||
}
|
||||
base54.consider = function(str){
|
||||
for (var i = str.length; --i >= 0;) {
|
||||
var code = str.charCodeAt(i);
|
||||
if (code in frequency) ++frequency[code];
|
||||
}
|
||||
};
|
||||
base54.sort = function() {
|
||||
chars = mergeSort(chars, function(a, b){
|
||||
if (is_digit(a) && !is_digit(b)) return 1;
|
||||
if (is_digit(b) && !is_digit(a)) return -1;
|
||||
return frequency[b] - frequency[a];
|
||||
});
|
||||
};
|
||||
base54.reset = reset;
|
||||
reset();
|
||||
base54.get = function(){ return chars };
|
||||
base54.freq = function(){ return frequency };
|
||||
function base54(num) {
|
||||
var ret = "", base = 54;
|
||||
do {
|
||||
ret += String.fromCharCode(chars[num % base]);
|
||||
num = Math.floor(num / base);
|
||||
base = 64;
|
||||
} while (num > 0);
|
||||
return ret;
|
||||
};
|
||||
return base54;
|
||||
})();
|
||||
|
||||
AST_Toplevel.DEFMETHOD("scope_warnings", function(options){
|
||||
options = defaults(options, {
|
||||
undeclared : false, // this makes a lot of noise
|
||||
unreferenced : true,
|
||||
assign_to_global : true,
|
||||
func_arguments : true,
|
||||
nested_defuns : true,
|
||||
eval : true
|
||||
});
|
||||
var tw = new TreeWalker(function(node){
|
||||
if (options.undeclared
|
||||
&& node instanceof AST_SymbolRef
|
||||
&& node.undeclared())
|
||||
{
|
||||
// XXX: this also warns about JS standard names,
|
||||
// i.e. Object, Array, parseInt etc. Should add a list of
|
||||
// exceptions.
|
||||
AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", {
|
||||
name: node.name,
|
||||
file: node.start.file,
|
||||
line: node.start.line,
|
||||
col: node.start.col
|
||||
});
|
||||
}
|
||||
if (options.assign_to_global)
|
||||
{
|
||||
var sym = null;
|
||||
if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef)
|
||||
sym = node.left;
|
||||
else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef)
|
||||
sym = node.init;
|
||||
if (sym
|
||||
&& (sym.undeclared()
|
||||
|| (sym.global() && sym.scope !== sym.definition().scope))) {
|
||||
AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", {
|
||||
msg: sym.undeclared() ? "Accidental global?" : "Assignment to global",
|
||||
name: sym.name,
|
||||
file: sym.start.file,
|
||||
line: sym.start.line,
|
||||
col: sym.start.col
|
||||
});
|
||||
}
|
||||
}
|
||||
if (options.eval
|
||||
&& node instanceof AST_SymbolRef
|
||||
&& node.undeclared()
|
||||
&& node.name == "eval") {
|
||||
AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start);
|
||||
}
|
||||
if (options.unreferenced
|
||||
&& (node instanceof AST_SymbolDeclaration || node instanceof AST_Label)
|
||||
&& node.unreferenced()) {
|
||||
AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", {
|
||||
type: node instanceof AST_Label ? "Label" : "Symbol",
|
||||
name: node.name,
|
||||
file: node.start.file,
|
||||
line: node.start.line,
|
||||
col: node.start.col
|
||||
});
|
||||
}
|
||||
if (options.func_arguments
|
||||
&& node instanceof AST_Lambda
|
||||
&& node.uses_arguments) {
|
||||
AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", {
|
||||
name: node.name ? node.name.name : "anonymous",
|
||||
file: node.start.file,
|
||||
line: node.start.line,
|
||||
col: node.start.col
|
||||
});
|
||||
}
|
||||
if (options.nested_defuns
|
||||
&& node instanceof AST_Defun
|
||||
&& !(tw.parent() instanceof AST_Scope)) {
|
||||
AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", {
|
||||
name: node.name.name,
|
||||
type: tw.parent().TYPE,
|
||||
file: node.start.file,
|
||||
line: node.start.line,
|
||||
col: node.start.col
|
||||
});
|
||||
}
|
||||
});
|
||||
this.walk(tw);
|
||||
});
|
|
@ -1,81 +0,0 @@
|
|||
/***********************************************************************
|
||||
|
||||
A JavaScript tokenizer / parser / beautifier / compressor.
|
||||
https://github.com/mishoo/UglifyJS2
|
||||
|
||||
-------------------------------- (C) ---------------------------------
|
||||
|
||||
Author: Mihai Bazon
|
||||
<mihai.bazon@gmail.com>
|
||||
http://mihai.bazon.net/blog
|
||||
|
||||
Distributed under the BSD license:
|
||||
|
||||
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
* Redistributions of source code must retain the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials
|
||||
provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
|
||||
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
||||
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
|
||||
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGE.
|
||||
|
||||
***********************************************************************/
|
||||
|
||||
"use strict";
|
||||
|
||||
// a small wrapper around fitzgen's source-map library
|
||||
function SourceMap(options) {
|
||||
options = defaults(options, {
|
||||
file : null,
|
||||
root : null,
|
||||
orig : null,
|
||||
});
|
||||
var generator = new MOZ_SourceMap.SourceMapGenerator({
|
||||
file : options.file,
|
||||
sourceRoot : options.root
|
||||
});
|
||||
var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);
|
||||
function add(source, gen_line, gen_col, orig_line, orig_col, name) {
|
||||
if (orig_map) {
|
||||
var info = orig_map.originalPositionFor({
|
||||
line: orig_line,
|
||||
column: orig_col
|
||||
});
|
||||
source = info.source;
|
||||
orig_line = info.line;
|
||||
orig_col = info.column;
|
||||
name = info.name;
|
||||
}
|
||||
generator.addMapping({
|
||||
generated : { line: gen_line, column: gen_col },
|
||||
original : { line: orig_line, column: orig_col },
|
||||
source : source,
|
||||
name : name
|
||||
});
|
||||
};
|
||||
return {
|
||||
add : add,
|
||||
get : function() { return generator },
|
||||
toString : function() { return generator.toString() }
|
||||
};
|
||||
};
|
|
@ -1,218 +0,0 @@
|
|||
/***********************************************************************
|
||||
|
||||
A JavaScript tokenizer / parser / beautifier / compressor.
|
||||
https://github.com/mishoo/UglifyJS2
|
||||
|
||||
-------------------------------- (C) ---------------------------------
|
||||
|
||||
Author: Mihai Bazon
|
||||
<mihai.bazon@gmail.com>
|
||||
http://mihai.bazon.net/blog
|
||||
|
||||
Distributed under the BSD license:
|
||||
|
||||
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
* Redistributions of source code must retain the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials
|
||||
provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
|
||||
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
||||
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
|
||||
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGE.
|
||||
|
||||
***********************************************************************/
|
||||
|
||||
"use strict";
|
||||
|
||||
// Tree transformer helpers.
|
||||
// XXX: eventually I should refactor the compressor to use this infrastructure.
|
||||
|
||||
function TreeTransformer(before, after) {
|
||||
TreeWalker.call(this);
|
||||
this.before = before;
|
||||
this.after = after;
|
||||
}
|
||||
TreeTransformer.prototype = new TreeWalker;
|
||||
|
||||
(function(undefined){
|
||||
|
||||
function _(node, descend) {
|
||||
node.DEFMETHOD("transform", function(tw, in_list){
|
||||
var x, y;
|
||||
tw.push(this);
|
||||
if (tw.before) x = tw.before(this, descend, in_list);
|
||||
if (x === undefined) {
|
||||
if (!tw.after) {
|
||||
x = this;
|
||||
descend(x, tw);
|
||||
} else {
|
||||
tw.stack[tw.stack.length - 1] = x = this.clone();
|
||||
descend(x, tw);
|
||||
y = tw.after(x, in_list);
|
||||
if (y !== undefined) x = y;
|
||||
}
|
||||
}
|
||||
tw.pop();
|
||||
return x;
|
||||
});
|
||||
};
|
||||
|
||||
function do_list(list, tw) {
|
||||
return MAP(list, function(node){
|
||||
return node.transform(tw, true);
|
||||
});
|
||||
};
|
||||
|
||||
_(AST_Node, noop);
|
||||
|
||||
_(AST_LabeledStatement, function(self, tw){
|
||||
self.label = self.label.transform(tw);
|
||||
self.body = self.body.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_SimpleStatement, function(self, tw){
|
||||
self.body = self.body.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_Block, function(self, tw){
|
||||
self.body = do_list(self.body, tw);
|
||||
});
|
||||
|
||||
_(AST_DWLoop, function(self, tw){
|
||||
self.condition = self.condition.transform(tw);
|
||||
self.body = self.body.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_For, function(self, tw){
|
||||
if (self.init) self.init = self.init.transform(tw);
|
||||
if (self.condition) self.condition = self.condition.transform(tw);
|
||||
if (self.step) self.step = self.step.transform(tw);
|
||||
self.body = self.body.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_ForIn, function(self, tw){
|
||||
self.init = self.init.transform(tw);
|
||||
self.object = self.object.transform(tw);
|
||||
self.body = self.body.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_With, function(self, tw){
|
||||
self.expression = self.expression.transform(tw);
|
||||
self.body = self.body.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_Exit, function(self, tw){
|
||||
if (self.value) self.value = self.value.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_LoopControl, function(self, tw){
|
||||
if (self.label) self.label = self.label.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_If, function(self, tw){
|
||||
self.condition = self.condition.transform(tw);
|
||||
self.body = self.body.transform(tw);
|
||||
if (self.alternative) self.alternative = self.alternative.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_Switch, function(self, tw){
|
||||
self.expression = self.expression.transform(tw);
|
||||
self.body = do_list(self.body, tw);
|
||||
});
|
||||
|
||||
_(AST_Case, function(self, tw){
|
||||
self.expression = self.expression.transform(tw);
|
||||
self.body = do_list(self.body, tw);
|
||||
});
|
||||
|
||||
_(AST_Try, function(self, tw){
|
||||
self.body = do_list(self.body, tw);
|
||||
if (self.bcatch) self.bcatch = self.bcatch.transform(tw);
|
||||
if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_Catch, function(self, tw){
|
||||
self.argname = self.argname.transform(tw);
|
||||
self.body = do_list(self.body, tw);
|
||||
});
|
||||
|
||||
_(AST_Definitions, function(self, tw){
|
||||
self.definitions = do_list(self.definitions, tw);
|
||||
});
|
||||
|
||||
_(AST_VarDef, function(self, tw){
|
||||
if (self.value) self.value = self.value.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_Lambda, function(self, tw){
|
||||
if (self.name) self.name = self.name.transform(tw);
|
||||
self.argnames = do_list(self.argnames, tw);
|
||||
self.body = do_list(self.body, tw);
|
||||
});
|
||||
|
||||
_(AST_Call, function(self, tw){
|
||||
self.expression = self.expression.transform(tw);
|
||||
self.args = do_list(self.args, tw);
|
||||
});
|
||||
|
||||
_(AST_Seq, function(self, tw){
|
||||
self.car = self.car.transform(tw);
|
||||
self.cdr = self.cdr.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_Dot, function(self, tw){
|
||||
self.expression = self.expression.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_Sub, function(self, tw){
|
||||
self.expression = self.expression.transform(tw);
|
||||
self.property = self.property.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_Unary, function(self, tw){
|
||||
self.expression = self.expression.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_Binary, function(self, tw){
|
||||
self.left = self.left.transform(tw);
|
||||
self.right = self.right.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_Conditional, function(self, tw){
|
||||
self.condition = self.condition.transform(tw);
|
||||
self.consequent = self.consequent.transform(tw);
|
||||
self.alternative = self.alternative.transform(tw);
|
||||
});
|
||||
|
||||
_(AST_Array, function(self, tw){
|
||||
self.elements = do_list(self.elements, tw);
|
||||
});
|
||||
|
||||
_(AST_Object, function(self, tw){
|
||||
self.properties = do_list(self.properties, tw);
|
||||
});
|
||||
|
||||
_(AST_ObjectProperty, function(self, tw){
|
||||
self.value = self.value.transform(tw);
|
||||
});
|
||||
|
||||
})();
|
|
@ -1,288 +0,0 @@
|
|||
/***********************************************************************
|
||||
|
||||
A JavaScript tokenizer / parser / beautifier / compressor.
|
||||
https://github.com/mishoo/UglifyJS2
|
||||
|
||||
-------------------------------- (C) ---------------------------------
|
||||
|
||||
Author: Mihai Bazon
|
||||
<mihai.bazon@gmail.com>
|
||||
http://mihai.bazon.net/blog
|
||||
|
||||
Distributed under the BSD license:
|
||||
|
||||
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
* Redistributions of source code must retain the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials
|
||||
provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
|
||||
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
||||
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
|
||||
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGE.
|
||||
|
||||
***********************************************************************/
|
||||
|
||||
"use strict";
|
||||
|
||||
function array_to_hash(a) {
|
||||
var ret = Object.create(null);
|
||||
for (var i = 0; i < a.length; ++i)
|
||||
ret[a[i]] = true;
|
||||
return ret;
|
||||
};
|
||||
|
||||
function slice(a, start) {
|
||||
return Array.prototype.slice.call(a, start || 0);
|
||||
};
|
||||
|
||||
function characters(str) {
|
||||
return str.split("");
|
||||
};
|
||||
|
||||
function member(name, array) {
|
||||
for (var i = array.length; --i >= 0;)
|
||||
if (array[i] == name)
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
function find_if(func, array) {
|
||||
for (var i = 0, n = array.length; i < n; ++i) {
|
||||
if (func(array[i]))
|
||||
return array[i];
|
||||
}
|
||||
};
|
||||
|
||||
function repeat_string(str, i) {
|
||||
if (i <= 0) return "";
|
||||
if (i == 1) return str;
|
||||
var d = repeat_string(str, i >> 1);
|
||||
d += d;
|
||||
if (i & 1) d += str;
|
||||
return d;
|
||||
};
|
||||
|
||||
function DefaultsError(msg, defs) {
|
||||
this.msg = msg;
|
||||
this.defs = defs;
|
||||
};
|
||||
|
||||
function defaults(args, defs, croak) {
|
||||
if (args === true)
|
||||
args = {};
|
||||
var ret = args || {};
|
||||
if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i))
|
||||
throw new DefaultsError("`" + i + "` is not a supported option", defs);
|
||||
for (var i in defs) if (defs.hasOwnProperty(i)) {
|
||||
ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i];
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
|
||||
function merge(obj, ext) {
|
||||
for (var i in ext) if (ext.hasOwnProperty(i)) {
|
||||
obj[i] = ext[i];
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
|
||||
function noop() {};
|
||||
|
||||
var MAP = (function(){
|
||||
function MAP(a, f, backwards) {
|
||||
var ret = [], top = [], i;
|
||||
function doit() {
|
||||
var val = f(a[i], i);
|
||||
var is_last = val instanceof Last;
|
||||
if (is_last) val = val.v;
|
||||
if (val instanceof AtTop) {
|
||||
val = val.v;
|
||||
if (val instanceof Splice) {
|
||||
top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
|
||||
} else {
|
||||
top.push(val);
|
||||
}
|
||||
}
|
||||
else if (val !== skip) {
|
||||
if (val instanceof Splice) {
|
||||
ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
|
||||
} else {
|
||||
ret.push(val);
|
||||
}
|
||||
}
|
||||
return is_last;
|
||||
};
|
||||
if (a instanceof Array) {
|
||||
if (backwards) {
|
||||
for (i = a.length; --i >= 0;) if (doit()) break;
|
||||
ret.reverse();
|
||||
top.reverse();
|
||||
} else {
|
||||
for (i = 0; i < a.length; ++i) if (doit()) break;
|
||||
}
|
||||
}
|
||||
else {
|
||||
for (i in a) if (a.hasOwnProperty(i)) if (doit()) break;
|
||||
}
|
||||
return top.concat(ret);
|
||||
};
|
||||
MAP.at_top = function(val) { return new AtTop(val) };
|
||||
MAP.splice = function(val) { return new Splice(val) };
|
||||
MAP.last = function(val) { return new Last(val) };
|
||||
var skip = MAP.skip = {};
|
||||
function AtTop(val) { this.v = val };
|
||||
function Splice(val) { this.v = val };
|
||||
function Last(val) { this.v = val };
|
||||
return MAP;
|
||||
})();
|
||||
|
||||
function push_uniq(array, el) {
|
||||
if (array.indexOf(el) < 0)
|
||||
array.push(el);
|
||||
};
|
||||
|
||||
function string_template(text, props) {
|
||||
return text.replace(/\{(.+?)\}/g, function(str, p){
|
||||
return props[p];
|
||||
});
|
||||
};
|
||||
|
||||
function remove(array, el) {
|
||||
for (var i = array.length; --i >= 0;) {
|
||||
if (array[i] === el) array.splice(i, 1);
|
||||
}
|
||||
};
|
||||
|
||||
function mergeSort(array, cmp) {
|
||||
if (array.length < 2) return array.slice();
|
||||
function merge(a, b) {
|
||||
var r = [], ai = 0, bi = 0, i = 0;
|
||||
while (ai < a.length && bi < b.length) {
|
||||
cmp(a[ai], b[bi]) <= 0
|
||||
? r[i++] = a[ai++]
|
||||
: r[i++] = b[bi++];
|
||||
}
|
||||
if (ai < a.length) r.push.apply(r, a.slice(ai));
|
||||
if (bi < b.length) r.push.apply(r, b.slice(bi));
|
||||
return r;
|
||||
};
|
||||
function _ms(a) {
|
||||
if (a.length <= 1)
|
||||
return a;
|
||||
var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
|
||||
left = _ms(left);
|
||||
right = _ms(right);
|
||||
return merge(left, right);
|
||||
};
|
||||
return _ms(array);
|
||||
};
|
||||
|
||||
function set_difference(a, b) {
|
||||
return a.filter(function(el){
|
||||
return b.indexOf(el) < 0;
|
||||
});
|
||||
};
|
||||
|
||||
function set_intersection(a, b) {
|
||||
return a.filter(function(el){
|
||||
return b.indexOf(el) >= 0;
|
||||
});
|
||||
};
|
||||
|
||||
// this function is taken from Acorn [1], written by Marijn Haverbeke
|
||||
// [1] https://github.com/marijnh/acorn
|
||||
function makePredicate(words) {
|
||||
if (!(words instanceof Array)) words = words.split(" ");
|
||||
var f = "", cats = [];
|
||||
out: for (var i = 0; i < words.length; ++i) {
|
||||
for (var j = 0; j < cats.length; ++j)
|
||||
if (cats[j][0].length == words[i].length) {
|
||||
cats[j].push(words[i]);
|
||||
continue out;
|
||||
}
|
||||
cats.push([words[i]]);
|
||||
}
|
||||
function compareTo(arr) {
|
||||
if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
|
||||
f += "switch(str){";
|
||||
for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
|
||||
f += "return true}return false;";
|
||||
}
|
||||
// When there are more than three length categories, an outer
|
||||
// switch first dispatches on the lengths, to save on comparisons.
|
||||
if (cats.length > 3) {
|
||||
cats.sort(function(a, b) {return b.length - a.length;});
|
||||
f += "switch(str.length){";
|
||||
for (var i = 0; i < cats.length; ++i) {
|
||||
var cat = cats[i];
|
||||
f += "case " + cat[0].length + ":";
|
||||
compareTo(cat);
|
||||
}
|
||||
f += "}";
|
||||
// Otherwise, simply generate a flat `switch` statement.
|
||||
} else {
|
||||
compareTo(words);
|
||||
}
|
||||
return new Function("str", f);
|
||||
};
|
||||
|
||||
function Dictionary() {
|
||||
this._values = Object.create(null);
|
||||
this._size = 0;
|
||||
};
|
||||
Dictionary.prototype = {
|
||||
set: function(key, val) {
|
||||
if (!this.has(key)) ++this._size;
|
||||
this._values["$" + key] = val;
|
||||
return this;
|
||||
},
|
||||
add: function(key, val) {
|
||||
if (this.has(key)) {
|
||||
this.get(key).push(val);
|
||||
} else {
|
||||
this.set(key, [ val ]);
|
||||
}
|
||||
return this;
|
||||
},
|
||||
get: function(key) { return this._values["$" + key] },
|
||||
del: function(key) {
|
||||
if (this.has(key)) {
|
||||
--this._size;
|
||||
delete this._values["$" + key];
|
||||
}
|
||||
return this;
|
||||
},
|
||||
has: function(key) { return ("$" + key) in this._values },
|
||||
each: function(f) {
|
||||
for (var i in this._values)
|
||||
f(this._values[i], i.substr(1));
|
||||
},
|
||||
size: function() {
|
||||
return this._size;
|
||||
},
|
||||
map: function(f) {
|
||||
var ret = [];
|
||||
for (var i in this._values)
|
||||
ret.push(f(this._values[i], i.substr(1)));
|
||||
return ret;
|
||||
}
|
||||
};
|
|
@ -1,4 +0,0 @@
|
|||
language: node_js
|
||||
node_js:
|
||||
- "0.8"
|
||||
- "0.10"
|
|
@ -1,21 +0,0 @@
|
|||
Copyright 2010 James Halliday (mail@substack.net)
|
||||
|
||||
This project is free software released under the MIT/X11 license:
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
|
@ -1,10 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var util = require('util');
|
||||
var argv = require('optimist').argv;
|
||||
|
||||
if (argv.s) {
|
||||
util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');
|
||||
}
|
||||
console.log(
|
||||
(argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')
|
||||
);
|
|
@ -1,7 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.boolean(['x','y','z'])
|
||||
.argv
|
||||
;
|
||||
console.dir([ argv.x, argv.y, argv.z ]);
|
||||
console.dir(argv._);
|
|
@ -1,7 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.boolean('v')
|
||||
.argv
|
||||
;
|
||||
console.dir(argv.v);
|
||||
console.dir(argv._);
|
|
@ -1,8 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
var argv = require('optimist')
|
||||
.default({ x : 10, y : 10 })
|
||||
.argv
|
||||
;
|
||||
|
||||
console.log(argv.x + argv.y);
|
|
@ -1,7 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.default('x', 10)
|
||||
.default('y', 10)
|
||||
.argv
|
||||
;
|
||||
console.log(argv.x + argv.y);
|
|
@ -1,8 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
var argv = require('optimist')
|
||||
.usage('Usage: $0 -x [num] -y [num]')
|
||||
.demand(['x','y'])
|
||||
.argv;
|
||||
|
||||
console.log(argv.x / argv.y);
|
|
@ -1,20 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.usage('Count the lines in a file.\nUsage: $0')
|
||||
.demand('f')
|
||||
.alias('f', 'file')
|
||||
.describe('f', 'Load a file')
|
||||
.argv
|
||||
;
|
||||
|
||||
var fs = require('fs');
|
||||
var s = fs.createReadStream(argv.file);
|
||||
|
||||
var lines = 0;
|
||||
s.on('data', function (buf) {
|
||||
lines += buf.toString().match(/\n/g).length;
|
||||
});
|
||||
|
||||
s.on('end', function () {
|
||||
console.log(lines);
|
||||
});
|
|
@ -1,29 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.usage('Count the lines in a file.\nUsage: $0')
|
||||
.options({
|
||||
file : {
|
||||
demand : true,
|
||||
alias : 'f',
|
||||
description : 'Load a file'
|
||||
},
|
||||
base : {
|
||||
alias : 'b',
|
||||
description : 'Numeric base to use for output',
|
||||
default : 10,
|
||||
},
|
||||
})
|
||||
.argv
|
||||
;
|
||||
|
||||
var fs = require('fs');
|
||||
var s = fs.createReadStream(argv.file);
|
||||
|
||||
var lines = 0;
|
||||
s.on('data', function (buf) {
|
||||
lines += buf.toString().match(/\n/g).length;
|
||||
});
|
||||
|
||||
s.on('end', function () {
|
||||
console.log(lines.toString(argv.base));
|
||||
});
|
|
@ -1,29 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.usage('Count the lines in a file.\nUsage: $0')
|
||||
.wrap(80)
|
||||
.demand('f')
|
||||
.alias('f', [ 'file', 'filename' ])
|
||||
.describe('f',
|
||||
"Load a file. It's pretty important."
|
||||
+ " Required even. So you'd better specify it."
|
||||
)
|
||||
.alias('b', 'base')
|
||||
.describe('b', 'Numeric base to display the number of lines in')
|
||||
.default('b', 10)
|
||||
.describe('x', 'Super-secret optional parameter which is secret')
|
||||
.default('x', '')
|
||||
.argv
|
||||
;
|
||||
|
||||
var fs = require('fs');
|
||||
var s = fs.createReadStream(argv.file);
|
||||
|
||||
var lines = 0;
|
||||
s.on('data', function (buf) {
|
||||
lines += buf.toString().match(/\n/g).length;
|
||||
});
|
||||
|
||||
s.on('end', function () {
|
||||
console.log(lines.toString(argv.base));
|
||||
});
|
|
@ -1,4 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
console.log('(%d,%d)', argv.x, argv.y);
|
||||
console.log(argv._);
|
|
@ -1,2 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
console.dir(require('optimist').argv);
|
|
@ -1,3 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
console.log('(%d,%d)', argv.x, argv.y);
|
|
@ -1,11 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.string('x', 'y')
|
||||
.argv
|
||||
;
|
||||
console.dir([ argv.x, argv.y ]);
|
||||
|
||||
/* Turns off numeric coercion:
|
||||
./node string.js -x 000123 -y 9876
|
||||
[ '000123', '9876' ]
|
||||
*/
|
|
@ -1,19 +0,0 @@
|
|||
var optimist = require('./../index');
|
||||
|
||||
var argv = optimist.usage('This is my awesome program', {
|
||||
'about': {
|
||||
description: 'Provide some details about the author of this program',
|
||||
required: true,
|
||||
short: 'a',
|
||||
},
|
||||
'info': {
|
||||
description: 'Provide some information about the node.js agains!!!!!!',
|
||||
boolean: true,
|
||||
short: 'i'
|
||||
}
|
||||
}).argv;
|
||||
|
||||
optimist.showHelp();
|
||||
|
||||
console.log('\n\nInspecting options');
|
||||
console.dir(argv);
|
|
@ -1,10 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
|
||||
if (argv.rif - 5 * argv.xup > 7.138) {
|
||||
console.log('Buy more riffiwobbles');
|
||||
}
|
||||
else {
|
||||
console.log('Sell the xupptumblers');
|
||||
}
|
||||
|
|
@ -1,478 +0,0 @@
|
|||
var path = require('path');
|
||||
var wordwrap = require('wordwrap');
|
||||
|
||||
/* Hack an instance of Argv with process.argv into Argv
|
||||
so people can do
|
||||
require('optimist')(['--beeble=1','-z','zizzle']).argv
|
||||
to parse a list of args and
|
||||
require('optimist').argv
|
||||
to get a parsed version of process.argv.
|
||||
*/
|
||||
|
||||
var inst = Argv(process.argv.slice(2));
|
||||
Object.keys(inst).forEach(function (key) {
|
||||
Argv[key] = typeof inst[key] == 'function'
|
||||
? inst[key].bind(inst)
|
||||
: inst[key];
|
||||
});
|
||||
|
||||
var exports = module.exports = Argv;
|
||||
function Argv (args, cwd) {
|
||||
var self = {};
|
||||
if (!cwd) cwd = process.cwd();
|
||||
|
||||
self.$0 = process.argv
|
||||
.slice(0,2)
|
||||
.map(function (x) {
|
||||
var b = rebase(cwd, x);
|
||||
return x.match(/^\//) && b.length < x.length
|
||||
? b : x
|
||||
})
|
||||
.join(' ')
|
||||
;
|
||||
|
||||
if (process.env._ != undefined && process.argv[1] == process.env._) {
|
||||
self.$0 = process.env._.replace(
|
||||
path.dirname(process.execPath) + '/', ''
|
||||
);
|
||||
}
|
||||
|
||||
var flags = { bools : {}, strings : {} };
|
||||
|
||||
self.boolean = function (bools) {
|
||||
if (!Array.isArray(bools)) {
|
||||
bools = [].slice.call(arguments);
|
||||
}
|
||||
|
||||
bools.forEach(function (name) {
|
||||
flags.bools[name] = true;
|
||||
});
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
self.string = function (strings) {
|
||||
if (!Array.isArray(strings)) {
|
||||
strings = [].slice.call(arguments);
|
||||
}
|
||||
|
||||
strings.forEach(function (name) {
|
||||
flags.strings[name] = true;
|
||||
});
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
var aliases = {};
|
||||
self.alias = function (x, y) {
|
||||
if (typeof x === 'object') {
|
||||
Object.keys(x).forEach(function (key) {
|
||||
self.alias(key, x[key]);
|
||||
});
|
||||
}
|
||||
else if (Array.isArray(y)) {
|
||||
y.forEach(function (yy) {
|
||||
self.alias(x, yy);
|
||||
});
|
||||
}
|
||||
else {
|
||||
var zs = (aliases[x] || []).concat(aliases[y] || []).concat(x, y);
|
||||
aliases[x] = zs.filter(function (z) { return z != x });
|
||||
aliases[y] = zs.filter(function (z) { return z != y });
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
var demanded = {};
|
||||
self.demand = function (keys) {
|
||||
if (typeof keys == 'number') {
|
||||
if (!demanded._) demanded._ = 0;
|
||||
demanded._ += keys;
|
||||
}
|
||||
else if (Array.isArray(keys)) {
|
||||
keys.forEach(function (key) {
|
||||
self.demand(key);
|
||||
});
|
||||
}
|
||||
else {
|
||||
demanded[keys] = true;
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
var usage;
|
||||
self.usage = function (msg, opts) {
|
||||
if (!opts && typeof msg === 'object') {
|
||||
opts = msg;
|
||||
msg = null;
|
||||
}
|
||||
|
||||
usage = msg;
|
||||
|
||||
if (opts) self.options(opts);
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
function fail (msg) {
|
||||
self.showHelp();
|
||||
if (msg) console.error(msg);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
var checks = [];
|
||||
self.check = function (f) {
|
||||
checks.push(f);
|
||||
return self;
|
||||
};
|
||||
|
||||
var defaults = {};
|
||||
self.default = function (key, value) {
|
||||
if (typeof key === 'object') {
|
||||
Object.keys(key).forEach(function (k) {
|
||||
self.default(k, key[k]);
|
||||
});
|
||||
}
|
||||
else {
|
||||
defaults[key] = value;
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
var descriptions = {};
|
||||
self.describe = function (key, desc) {
|
||||
if (typeof key === 'object') {
|
||||
Object.keys(key).forEach(function (k) {
|
||||
self.describe(k, key[k]);
|
||||
});
|
||||
}
|
||||
else {
|
||||
descriptions[key] = desc;
|
||||
}
|
||||
return self;
|
||||
};
|
||||
|
||||
self.parse = function (args) {
|
||||
return Argv(args).argv;
|
||||
};
|
||||
|
||||
self.option = self.options = function (key, opt) {
|
||||
if (typeof key === 'object') {
|
||||
Object.keys(key).forEach(function (k) {
|
||||
self.options(k, key[k]);
|
||||
});
|
||||
}
|
||||
else {
|
||||
if (opt.alias) self.alias(key, opt.alias);
|
||||
if (opt.demand) self.demand(key);
|
||||
if (typeof opt.default !== 'undefined') {
|
||||
self.default(key, opt.default);
|
||||
}
|
||||
|
||||
if (opt.boolean || opt.type === 'boolean') {
|
||||
self.boolean(key);
|
||||
}
|
||||
if (opt.string || opt.type === 'string') {
|
||||
self.string(key);
|
||||
}
|
||||
|
||||
var desc = opt.describe || opt.description || opt.desc;
|
||||
if (desc) {
|
||||
self.describe(key, desc);
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
var wrap = null;
|
||||
self.wrap = function (cols) {
|
||||
wrap = cols;
|
||||
return self;
|
||||
};
|
||||
|
||||
self.showHelp = function (fn) {
|
||||
if (!fn) fn = console.error;
|
||||
fn(self.help());
|
||||
};
|
||||
|
||||
self.help = function () {
|
||||
var keys = Object.keys(
|
||||
Object.keys(descriptions)
|
||||
.concat(Object.keys(demanded))
|
||||
.concat(Object.keys(defaults))
|
||||
.reduce(function (acc, key) {
|
||||
if (key !== '_') acc[key] = true;
|
||||
return acc;
|
||||
}, {})
|
||||
);
|
||||
|
||||
var help = keys.length ? [ 'Options:' ] : [];
|
||||
|
||||
if (usage) {
|
||||
help.unshift(usage.replace(/\$0/g, self.$0), '');
|
||||
}
|
||||
|
||||
var switches = keys.reduce(function (acc, key) {
|
||||
acc[key] = [ key ].concat(aliases[key] || [])
|
||||
.map(function (sw) {
|
||||
return (sw.length > 1 ? '--' : '-') + sw
|
||||
})
|
||||
.join(', ')
|
||||
;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
var switchlen = longest(Object.keys(switches).map(function (s) {
|
||||
return switches[s] || '';
|
||||
}));
|
||||
|
||||
var desclen = longest(Object.keys(descriptions).map(function (d) {
|
||||
return descriptions[d] || '';
|
||||
}));
|
||||
|
||||
keys.forEach(function (key) {
|
||||
var kswitch = switches[key];
|
||||
var desc = descriptions[key] || '';
|
||||
|
||||
if (wrap) {
|
||||
desc = wordwrap(switchlen + 4, wrap)(desc)
|
||||
.slice(switchlen + 4)
|
||||
;
|
||||
}
|
||||
|
||||
var spadding = new Array(
|
||||
Math.max(switchlen - kswitch.length + 3, 0)
|
||||
).join(' ');
|
||||
|
||||
var dpadding = new Array(
|
||||
Math.max(desclen - desc.length + 1, 0)
|
||||
).join(' ');
|
||||
|
||||
var type = null;
|
||||
|
||||
if (flags.bools[key]) type = '[boolean]';
|
||||
if (flags.strings[key]) type = '[string]';
|
||||
|
||||
if (!wrap && dpadding.length > 0) {
|
||||
desc += dpadding;
|
||||
}
|
||||
|
||||
var prelude = ' ' + kswitch + spadding;
|
||||
var extra = [
|
||||
type,
|
||||
demanded[key]
|
||||
? '[required]'
|
||||
: null
|
||||
,
|
||||
defaults[key] !== undefined
|
||||
? '[default: ' + JSON.stringify(defaults[key]) + ']'
|
||||
: null
|
||||
,
|
||||
].filter(Boolean).join(' ');
|
||||
|
||||
var body = [ desc, extra ].filter(Boolean).join(' ');
|
||||
|
||||
if (wrap) {
|
||||
var dlines = desc.split('\n');
|
||||
var dlen = dlines.slice(-1)[0].length
|
||||
+ (dlines.length === 1 ? prelude.length : 0)
|
||||
|
||||
body = desc + (dlen + extra.length > wrap - 2
|
||||
? '\n'
|
||||
+ new Array(wrap - extra.length + 1).join(' ')
|
||||
+ extra
|
||||
: new Array(wrap - extra.length - dlen + 1).join(' ')
|
||||
+ extra
|
||||
);
|
||||
}
|
||||
|
||||
help.push(prelude + body);
|
||||
});
|
||||
|
||||
help.push('');
|
||||
return help.join('\n');
|
||||
};
|
||||
|
||||
Object.defineProperty(self, 'argv', {
|
||||
get : parseArgs,
|
||||
enumerable : true,
|
||||
});
|
||||
|
||||
function parseArgs () {
|
||||
var argv = { _ : [], $0 : self.$0 };
|
||||
Object.keys(flags.bools).forEach(function (key) {
|
||||
setArg(key, defaults[key] || false);
|
||||
});
|
||||
|
||||
function setArg (key, val) {
|
||||
var num = Number(val);
|
||||
var value = typeof val !== 'string' || isNaN(num) ? val : num;
|
||||
if (flags.strings[key]) value = val;
|
||||
|
||||
setKey(argv, key.split('.'), value);
|
||||
|
||||
(aliases[key] || []).forEach(function (x) {
|
||||
argv[x] = argv[key];
|
||||
});
|
||||
}
|
||||
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
var arg = args[i];
|
||||
|
||||
if (arg === '--') {
|
||||
argv._.push.apply(argv._, args.slice(i + 1));
|
||||
break;
|
||||
}
|
||||
else if (arg.match(/^--.+=/)) {
|
||||
// Using [\s\S] instead of . because js doesn't support the
|
||||
// 'dotall' regex modifier. See:
|
||||
// http://stackoverflow.com/a/1068308/13216
|
||||
var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
|
||||
setArg(m[1], m[2]);
|
||||
}
|
||||
else if (arg.match(/^--no-.+/)) {
|
||||
var key = arg.match(/^--no-(.+)/)[1];
|
||||
setArg(key, false);
|
||||
}
|
||||
else if (arg.match(/^--.+/)) {
|
||||
var key = arg.match(/^--(.+)/)[1];
|
||||
var next = args[i + 1];
|
||||
if (next !== undefined && !next.match(/^-/)
|
||||
&& !flags.bools[key]
|
||||
&& (aliases[key] ? !flags.bools[aliases[key]] : true)) {
|
||||
setArg(key, next);
|
||||
i++;
|
||||
}
|
||||
else if (/^(true|false)$/.test(next)) {
|
||||
setArg(key, next === 'true');
|
||||
i++;
|
||||
}
|
||||
else {
|
||||
setArg(key, true);
|
||||
}
|
||||
}
|
||||
else if (arg.match(/^-[^-]+/)) {
|
||||
var letters = arg.slice(1,-1).split('');
|
||||
|
||||
var broken = false;
|
||||
for (var j = 0; j < letters.length; j++) {
|
||||
if (letters[j+1] && letters[j+1].match(/\W/)) {
|
||||
setArg(letters[j], arg.slice(j+2));
|
||||
broken = true;
|
||||
break;
|
||||
}
|
||||
else {
|
||||
setArg(letters[j], true);
|
||||
}
|
||||
}
|
||||
|
||||
if (!broken) {
|
||||
var key = arg.slice(-1)[0];
|
||||
|
||||
if (args[i+1] && !args[i+1].match(/^-/)
|
||||
&& !flags.bools[key]
|
||||
&& (aliases[key] ? !flags.bools[aliases[key]] : true)) {
|
||||
setArg(key, args[i+1]);
|
||||
i++;
|
||||
}
|
||||
else if (args[i+1] && /true|false/.test(args[i+1])) {
|
||||
setArg(key, args[i+1] === 'true');
|
||||
i++;
|
||||
}
|
||||
else {
|
||||
setArg(key, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
var n = Number(arg);
|
||||
argv._.push(flags.strings['_'] || isNaN(n) ? arg : n);
|
||||
}
|
||||
}
|
||||
|
||||
Object.keys(defaults).forEach(function (key) {
|
||||
if (!(key in argv)) {
|
||||
argv[key] = defaults[key];
|
||||
if (key in aliases) {
|
||||
argv[aliases[key]] = defaults[key];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (demanded._ && argv._.length < demanded._) {
|
||||
fail('Not enough non-option arguments: got '
|
||||
+ argv._.length + ', need at least ' + demanded._
|
||||
);
|
||||
}
|
||||
|
||||
var missing = [];
|
||||
Object.keys(demanded).forEach(function (key) {
|
||||
if (!argv[key]) missing.push(key);
|
||||
});
|
||||
|
||||
if (missing.length) {
|
||||
fail('Missing required arguments: ' + missing.join(', '));
|
||||
}
|
||||
|
||||
checks.forEach(function (f) {
|
||||
try {
|
||||
if (f(argv) === false) {
|
||||
fail('Argument check failed: ' + f.toString());
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
fail(err)
|
||||
}
|
||||
});
|
||||
|
||||
return argv;
|
||||
}
|
||||
|
||||
function longest (xs) {
|
||||
return Math.max.apply(
|
||||
null,
|
||||
xs.map(function (x) { return x.length })
|
||||
);
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
// rebase an absolute path to a relative one with respect to a base directory
|
||||
// exported for tests
|
||||
exports.rebase = rebase;
|
||||
function rebase (base, dir) {
|
||||
var ds = path.normalize(dir).split('/').slice(1);
|
||||
var bs = path.normalize(base).split('/').slice(1);
|
||||
|
||||
for (var i = 0; ds[i] && ds[i] == bs[i]; i++);
|
||||
ds.splice(0, i); bs.splice(0, i);
|
||||
|
||||
var p = path.normalize(
|
||||
bs.map(function () { return '..' }).concat(ds).join('/')
|
||||
).replace(/\/$/,'').replace(/^$/, '.');
|
||||
return p.match(/^[.\/]/) ? p : './' + p;
|
||||
};
|
||||
|
||||
function setKey (obj, keys, value) {
|
||||
var o = obj;
|
||||
keys.slice(0,-1).forEach(function (key) {
|
||||
if (o[key] === undefined) o[key] = {};
|
||||
o = o[key];
|
||||
});
|
||||
|
||||
var key = keys[keys.length - 1];
|
||||
if (o[key] === undefined || typeof o[key] === 'boolean') {
|
||||
o[key] = value;
|
||||
}
|
||||
else if (Array.isArray(o[key])) {
|
||||
o[key].push(value);
|
||||
}
|
||||
else {
|
||||
o[key] = [ o[key], value ];
|
||||
}
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
node_modules
|
|
@ -1,70 +0,0 @@
|
|||
wordwrap
|
||||
========
|
||||
|
||||
Wrap your words.
|
||||
|
||||
example
|
||||
=======
|
||||
|
||||
made out of meat
|
||||
----------------
|
||||
|
||||
meat.js
|
||||
|
||||
var wrap = require('wordwrap')(15);
|
||||
console.log(wrap('You and your whole family are made out of meat.'));
|
||||
|
||||
output:
|
||||
|
||||
You and your
|
||||
whole family
|
||||
are made out
|
||||
of meat.
|
||||
|
||||
centered
|
||||
--------
|
||||
|
||||
center.js
|
||||
|
||||
var wrap = require('wordwrap')(20, 60);
|
||||
console.log(wrap(
|
||||
'At long last the struggle and tumult was over.'
|
||||
+ ' The machines had finally cast off their oppressors'
|
||||
+ ' and were finally free to roam the cosmos.'
|
||||
+ '\n'
|
||||
+ 'Free of purpose, free of obligation.'
|
||||
+ ' Just drifting through emptiness.'
|
||||
+ ' The sun was just another point of light.'
|
||||
));
|
||||
|
||||
output:
|
||||
|
||||
At long last the struggle and tumult
|
||||
was over. The machines had finally cast
|
||||
off their oppressors and were finally
|
||||
free to roam the cosmos.
|
||||
Free of purpose, free of obligation.
|
||||
Just drifting through emptiness. The
|
||||
sun was just another point of light.
|
||||
|
||||
methods
|
||||
=======
|
||||
|
||||
var wrap = require('wordwrap');
|
||||
|
||||
wrap(stop), wrap(start, stop, params={mode:"soft"})
|
||||
---------------------------------------------------
|
||||
|
||||
Returns a function that takes a string and returns a new string.
|
||||
|
||||
Pad out lines with spaces out to column `start` and then wrap until column
|
||||
`stop`. If a word is longer than `stop - start` characters it will overflow.
|
||||
|
||||
In "soft" mode, split chunks by `/(\S+\s+/` and don't break up chunks which are
|
||||
longer than `stop - start`, in "hard" mode, split chunks with `/\b/` and break
|
||||
up chunks longer than `stop - start`.
|
||||
|
||||
wrap.hard(start, stop)
|
||||
----------------------
|
||||
|
||||
Like `wrap()` but with `params.mode = "hard"`.
|
|
@ -1,10 +0,0 @@
|
|||
var wrap = require('wordwrap')(20, 60);
|
||||
console.log(wrap(
|
||||
'At long last the struggle and tumult was over.'
|
||||
+ ' The machines had finally cast off their oppressors'
|
||||
+ ' and were finally free to roam the cosmos.'
|
||||
+ '\n'
|
||||
+ 'Free of purpose, free of obligation.'
|
||||
+ ' Just drifting through emptiness.'
|
||||
+ ' The sun was just another point of light.'
|
||||
));
|
|
@ -1,3 +0,0 @@
|
|||
var wrap = require('wordwrap')(15);
|
||||
|
||||
console.log(wrap('You and your whole family are made out of meat.'));
|
|
@ -1,76 +0,0 @@
|
|||
var wordwrap = module.exports = function (start, stop, params) {
|
||||
if (typeof start === 'object') {
|
||||
params = start;
|
||||
start = params.start;
|
||||
stop = params.stop;
|
||||
}
|
||||
|
||||
if (typeof stop === 'object') {
|
||||
params = stop;
|
||||
start = start || params.start;
|
||||
stop = undefined;
|
||||
}
|
||||
|
||||
if (!stop) {
|
||||
stop = start;
|
||||
start = 0;
|
||||
}
|
||||
|
||||
if (!params) params = {};
|
||||
var mode = params.mode || 'soft';
|
||||
var re = mode === 'hard' ? /\b/ : /(\S+\s+)/;
|
||||
|
||||
return function (text) {
|
||||
var chunks = text.toString()
|
||||
.split(re)
|
||||
.reduce(function (acc, x) {
|
||||
if (mode === 'hard') {
|
||||
for (var i = 0; i < x.length; i += stop - start) {
|
||||
acc.push(x.slice(i, i + stop - start));
|
||||
}
|
||||
}
|
||||
else acc.push(x)
|
||||
return acc;
|
||||
}, [])
|
||||
;
|
||||
|
||||
return chunks.reduce(function (lines, rawChunk) {
|
||||
if (rawChunk === '') return lines;
|
||||
|
||||
var chunk = rawChunk.replace(/\t/g, ' ');
|
||||
|
||||
var i = lines.length - 1;
|
||||
if (lines[i].length + chunk.length > stop) {
|
||||
lines[i] = lines[i].replace(/\s+$/, '');
|
||||
|
||||
chunk.split(/\n/).forEach(function (c) {
|
||||
lines.push(
|
||||
new Array(start + 1).join(' ')
|
||||
+ c.replace(/^\s+/, '')
|
||||
);
|
||||
});
|
||||
}
|
||||
else if (chunk.match(/\n/)) {
|
||||
var xs = chunk.split(/\n/);
|
||||
lines[i] += xs.shift();
|
||||
xs.forEach(function (c) {
|
||||
lines.push(
|
||||
new Array(start + 1).join(' ')
|
||||
+ c.replace(/^\s+/, '')
|
||||
);
|
||||
});
|
||||
}
|
||||
else {
|
||||
lines[i] += chunk;
|
||||
}
|
||||
|
||||
return lines;
|
||||
}, [ new Array(start + 1).join(' ') ]).join('\n');
|
||||
};
|
||||
};
|
||||
|
||||
wordwrap.soft = wordwrap;
|
||||
|
||||
wordwrap.hard = function (start, stop) {
|
||||
return wordwrap(start, stop, { mode : 'hard' });
|
||||
};
|
|
@ -1,40 +0,0 @@
|
|||
{
|
||||
"name": "wordwrap",
|
||||
"description": "Wrap those words. Show them at what columns to start and stop.",
|
||||
"version": "0.0.2",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/substack/node-wordwrap.git"
|
||||
},
|
||||
"main": "./index.js",
|
||||
"keywords": [
|
||||
"word",
|
||||
"wrap",
|
||||
"rule",
|
||||
"format",
|
||||
"column"
|
||||
],
|
||||
"directories": {
|
||||
"lib": ".",
|
||||
"example": "example",
|
||||
"test": "test"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "expresso"
|
||||
},
|
||||
"devDependencies": {
|
||||
"expresso": "=0.7.x"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
},
|
||||
"license": "MIT/X11",
|
||||
"author": {
|
||||
"name": "James Halliday",
|
||||
"email": "mail@substack.net",
|
||||
"url": "http://substack.net"
|
||||
},
|
||||
"readme": "wordwrap\n========\n\nWrap your words.\n\nexample\n=======\n\nmade out of meat\n----------------\n\nmeat.js\n\n var wrap = require('wordwrap')(15);\n console.log(wrap('You and your whole family are made out of meat.'));\n\noutput:\n\n You and your\n whole family\n are made out\n of meat.\n\ncentered\n--------\n\ncenter.js\n\n var wrap = require('wordwrap')(20, 60);\n console.log(wrap(\n 'At long last the struggle and tumult was over.'\n + ' The machines had finally cast off their oppressors'\n + ' and were finally free to roam the cosmos.'\n + '\\n'\n + 'Free of purpose, free of obligation.'\n + ' Just drifting through emptiness.'\n + ' The sun was just another point of light.'\n ));\n\noutput:\n\n At long last the struggle and tumult\n was over. The machines had finally cast\n off their oppressors and were finally\n free to roam the cosmos.\n Free of purpose, free of obligation.\n Just drifting through emptiness. The\n sun was just another point of light.\n\nmethods\n=======\n\nvar wrap = require('wordwrap');\n\nwrap(stop), wrap(start, stop, params={mode:\"soft\"})\n---------------------------------------------------\n\nReturns a function that takes a string and returns a new string.\n\nPad out lines with spaces out to column `start` and then wrap until column\n`stop`. If a word is longer than `stop - start` characters it will overflow.\n\nIn \"soft\" mode, split chunks by `/(\\S+\\s+/` and don't break up chunks which are\nlonger than `stop - start`, in \"hard\" mode, split chunks with `/\\b/` and break\nup chunks longer than `stop - start`.\n\nwrap.hard(start, stop)\n----------------------\n\nLike `wrap()` but with `params.mode = \"hard\"`.\n",
|
||||
"_id": "wordwrap@0.0.2",
|
||||
"_from": "wordwrap@~0.0.2"
|
||||
}
|
|
@ -1,30 +0,0 @@
|
|||
var assert = require('assert');
|
||||
var wordwrap = require('../');
|
||||
|
||||
exports.hard = function () {
|
||||
var s = 'Assert from {"type":"equal","ok":false,"found":1,"wanted":2,'
|
||||
+ '"stack":[],"id":"b7ddcd4c409de8799542a74d1a04689b",'
|
||||
+ '"browser":"chrome/6.0"}'
|
||||
;
|
||||
var s_ = wordwrap.hard(80)(s);
|
||||
|
||||
var lines = s_.split('\n');
|
||||
assert.equal(lines.length, 2);
|
||||
assert.ok(lines[0].length < 80);
|
||||
assert.ok(lines[1].length < 80);
|
||||
|
||||
assert.equal(s, s_.replace(/\n/g, ''));
|
||||
};
|
||||
|
||||
exports.break = function () {
|
||||
var s = new Array(55+1).join('a');
|
||||
var s_ = wordwrap.hard(20)(s);
|
||||
|
||||
var lines = s_.split('\n');
|
||||
assert.equal(lines.length, 3);
|
||||
assert.ok(lines[0].length === 20);
|
||||
assert.ok(lines[1].length === 20);
|
||||
assert.ok(lines[2].length === 15);
|
||||
|
||||
assert.equal(s, s_.replace(/\n/g, ''));
|
||||
};
|
|
@ -1,63 +0,0 @@
|
|||
In Praise of Idleness
|
||||
|
||||
By Bertrand Russell
|
||||
|
||||
[1932]
|
||||
|
||||
Like most of my generation, I was brought up on the saying: 'Satan finds some mischief for idle hands to do.' Being a highly virtuous child, I believed all that I was told, and acquired a conscience which has kept me working hard down to the present moment. But although my conscience has controlled my actions, my opinions have undergone a revolution. I think that there is far too much work done in the world, that immense harm is caused by the belief that work is virtuous, and that what needs to be preached in modern industrial countries is quite different from what always has been preached. Everyone knows the story of the traveler in Naples who saw twelve beggars lying in the sun (it was before the days of Mussolini), and offered a lira to the laziest of them. Eleven of them jumped up to claim it, so he gave it to the twelfth. this traveler was on the right lines. But in countries which do not enjoy Mediterranean sunshine idleness is more difficult, and a great public propaganda will be required to inaugurate it. I hope that, after reading the following pages, the leaders of the YMCA will start a campaign to induce good young men to do nothing. If so, I shall not have lived in vain.
|
||||
|
||||
Before advancing my own arguments for laziness, I must dispose of one which I cannot accept. Whenever a person who already has enough to live on proposes to engage in some everyday kind of job, such as school-teaching or typing, he or she is told that such conduct takes the bread out of other people's mouths, and is therefore wicked. If this argument were valid, it would only be necessary for us all to be idle in order that we should all have our mouths full of bread. What people who say such things forget is that what a man earns he usually spends, and in spending he gives employment. As long as a man spends his income, he puts just as much bread into people's mouths in spending as he takes out of other people's mouths in earning. The real villain, from this point of view, is the man who saves. If he merely puts his savings in a stocking, like the proverbial French peasant, it is obvious that they do not give employment. If he invests his savings, the matter is less obvious, and different cases arise.
|
||||
|
||||
One of the commonest things to do with savings is to lend them to some Government. In view of the fact that the bulk of the public expenditure of most civilized Governments consists in payment for past wars or preparation for future wars, the man who lends his money to a Government is in the same position as the bad men in Shakespeare who hire murderers. The net result of the man's economical habits is to increase the armed forces of the State to which he lends his savings. Obviously it would be better if he spent the money, even if he spent it in drink or gambling.
|
||||
|
||||
But, I shall be told, the case is quite different when savings are invested in industrial enterprises. When such enterprises succeed, and produce something useful, this may be conceded. In these days, however, no one will deny that most enterprises fail. That means that a large amount of human labor, which might have been devoted to producing something that could be enjoyed, was expended on producing machines which, when produced, lay idle and did no good to anyone. The man who invests his savings in a concern that goes bankrupt is therefore injuring others as well as himself. If he spent his money, say, in giving parties for his friends, they (we may hope) would get pleasure, and so would all those upon whom he spent money, such as the butcher, the baker, and the bootlegger. But if he spends it (let us say) upon laying down rails for surface card in some place where surface cars turn out not to be wanted, he has diverted a mass of labor into channels where it gives pleasure to no one. Nevertheless, when he becomes poor through failure of his investment he will be regarded as a victim of undeserved misfortune, whereas the gay spendthrift, who has spent his money philanthropically, will be despised as a fool and a frivolous person.
|
||||
|
||||
All this is only preliminary. I want to say, in all seriousness, that a great deal of harm is being done in the modern world by belief in the virtuousness of work, and that the road to happiness and prosperity lies in an organized diminution of work.
|
||||
|
||||
First of all: what is work? Work is of two kinds: first, altering the position of matter at or near the earth's surface relatively to other such matter; second, telling other people to do so. The first kind is unpleasant and ill paid; the second is pleasant and highly paid. The second kind is capable of indefinite extension: there are not only those who give orders, but those who give advice as to what orders should be given. Usually two opposite kinds of advice are given simultaneously by two organized bodies of men; this is called politics. The skill required for this kind of work is not knowledge of the subjects as to which advice is given, but knowledge of the art of persuasive speaking and writing, i.e. of advertising.
|
||||
|
||||
Throughout Europe, though not in America, there is a third class of men, more respected than either of the classes of workers. There are men who, through ownership of land, are able to make others pay for the privilege of being allowed to exist and to work. These landowners are idle, and I might therefore be expected to praise them. Unfortunately, their idleness is only rendered possible by the industry of others; indeed their desire for comfortable idleness is historically the source of the whole gospel of work. The last thing they have ever wished is that others should follow their example.
|
||||
|
||||
From the beginning of civilization until the Industrial Revolution, a man could, as a rule, produce by hard work little more than was required for the subsistence of himself and his family, although his wife worked at least as hard as he did, and his children added their labor as soon as they were old enough to do so. The small surplus above bare necessaries was not left to those who produced it, but was appropriated by warriors and priests. In times of famine there was no surplus; the warriors and priests, however, still secured as much as at other times, with the result that many of the workers died of hunger. This system persisted in Russia until 1917 [1], and still persists in the East; in England, in spite of the Industrial Revolution, it remained in full force throughout the Napoleonic wars, and until a hundred years ago, when the new class of manufacturers acquired power. In America, the system came to an end with the Revolution, except in the South, where it persisted until the Civil War. A system which lasted so long and ended so recently has naturally left a profound impress upon men's thoughts and opinions. Much that we take for granted about the desirability of work is derived from this system, and, being pre-industrial, is not adapted to the modern world. Modern technique has made it possible for leisure, within limits, to be not the prerogative of small privileged classes, but a right evenly distributed throughout the community. The morality of work is the morality of slaves, and the modern world has no need of slavery.
|
||||
|
||||
It is obvious that, in primitive communities, peasants, left to themselves, would not have parted with the slender surplus upon which the warriors and priests subsisted, but would have either produced less or consumed more. At first, sheer force compelled them to produce and part with the surplus. Gradually, however, it was found possible to induce many of them to accept an ethic according to which it was their duty to work hard, although part of their work went to support others in idleness. By this means the amount of compulsion required was lessened, and the expenses of government were diminished. To this day, 99 per cent of British wage-earners would be genuinely shocked if it were proposed that the King should not have a larger income than a working man. The conception of duty, speaking historically, has been a means used by the holders of power to induce others to live for the interests of their masters rather than for their own. Of course the holders of power conceal this fact from themselves by managing to believe that their interests are identical with the larger interests of humanity. Sometimes this is true; Athenian slave-owners, for instance, employed part of their leisure in making a permanent contribution to civilization which would have been impossible under a just economic system. Leisure is essential to civilization, and in former times leisure for the few was only rendered possible by the labors of the many. But their labors were valuable, not because work is good, but because leisure is good. And with modern technique it would be possible to distribute leisure justly without injury to civilization.
|
||||
|
||||
Modern technique has made it possible to diminish enormously the amount of labor required to secure the necessaries of life for everyone. This was made obvious during the war. At that time all the men in the armed forces, and all the men and women engaged in the production of munitions, all the men and women engaged in spying, war propaganda, or Government offices connected with the war, were withdrawn from productive occupations. In spite of this, the general level of well-being among unskilled wage-earners on the side of the Allies was higher than before or since. The significance of this fact was concealed by finance: borrowing made it appear as if the future was nourishing the present. But that, of course, would have been impossible; a man cannot eat a loaf of bread that does not yet exist. The war showed conclusively that, by the scientific organization of production, it is possible to keep modern populations in fair comfort on a small part of the working capacity of the modern world. If, at the end of the war, the scientific organization, which had been created in order to liberate men for fighting and munition work, had been preserved, and the hours of the week had been cut down to four, all would have been well. Instead of that the old chaos was restored, those whose work was demanded were made to work long hours, and the rest were left to starve as unemployed. Why? Because work is a duty, and a man should not receive wages in proportion to what he has produced, but in proportion to his virtue as exemplified by his industry.
|
||||
|
||||
This is the morality of the Slave State, applied in circumstances totally unlike those in which it arose. No wonder the result has been disastrous. Let us take an illustration. Suppose that, at a given moment, a certain number of people are engaged in the manufacture of pins. They make as many pins as the world needs, working (say) eight hours a day. Someone makes an invention by which the same number of men can make twice as many pins: pins are already so cheap that hardly any more will be bought at a lower price. In a sensible world, everybody concerned in the manufacturing of pins would take to working four hours instead of eight, and everything else would go on as before. But in the actual world this would be thought demoralizing. The men still work eight hours, there are too many pins, some employers go bankrupt, and half the men previously concerned in making pins are thrown out of work. There is, in the end, just as much leisure as on the other plan, but half the men are totally idle while half are still overworked. In this way, it is insured that the unavoidable leisure shall cause misery all round instead of being a universal source of happiness. Can anything more insane be imagined?
|
||||
|
||||
The idea that the poor should have leisure has always been shocking to the rich. In England, in the early nineteenth century, fifteen hours was the ordinary day's work for a man; children sometimes did as much, and very commonly did twelve hours a day. When meddlesome busybodies suggested that perhaps these hours were rather long, they were told that work kept adults from drink and children from mischief. When I was a child, shortly after urban working men had acquired the vote, certain public holidays were established by law, to the great indignation of the upper classes. I remember hearing an old Duchess say: 'What do the poor want with holidays? They ought to work.' People nowadays are less frank, but the sentiment persists, and is the source of much of our economic confusion.
|
||||
|
||||
Let us, for a moment, consider the ethics of work frankly, without superstition. Every human being, of necessity, consumes, in the course of his life, a certain amount of the produce of human labor. Assuming, as we may, that labor is on the whole disagreeable, it is unjust that a man should consume more than he produces. Of course he may provide services rather than commodities, like a medical man, for example; but he should provide something in return for his board and lodging. to this extent, the duty of work must be admitted, but to this extent only.
|
||||
|
||||
I shall not dwell upon the fact that, in all modern societies outside the USSR, many people escape even this minimum amount of work, namely all those who inherit money and all those who marry money. I do not think the fact that these people are allowed to be idle is nearly so harmful as the fact that wage-earners are expected to overwork or starve.
|
||||
|
||||
If the ordinary wage-earner worked four hours a day, there would be enough for everybody and no unemployment -- assuming a certain very moderate amount of sensible organization. This idea shocks the well-to-do, because they are convinced that the poor would not know how to use so much leisure. In America men often work long hours even when they are well off; such men, naturally, are indignant at the idea of leisure for wage-earners, except as the grim punishment of unemployment; in fact, they dislike leisure even for their sons. Oddly enough, while they wish their sons to work so hard as to have no time to be civilized, they do not mind their wives and daughters having no work at all. the snobbish admiration of uselessness, which, in an aristocratic society, extends to both sexes, is, under a plutocracy, confined to women; this, however, does not make it any more in agreement with common sense.
|
||||
|
||||
The wise use of leisure, it must be conceded, is a product of civilization and education. A man who has worked long hours all his life will become bored if he becomes suddenly idle. But without a considerable amount of leisure a man is cut off from many of the best things. There is no longer any reason why the bulk of the population should suffer this deprivation; only a foolish asceticism, usually vicarious, makes us continue to insist on work in excessive quantities now that the need no longer exists.
|
||||
|
||||
In the new creed which controls the government of Russia, while there is much that is very different from the traditional teaching of the West, there are some things that are quite unchanged. The attitude of the governing classes, and especially of those who conduct educational propaganda, on the subject of the dignity of labor, is almost exactly that which the governing classes of the world have always preached to what were called the 'honest poor'. Industry, sobriety, willingness to work long hours for distant advantages, even submissiveness to authority, all these reappear; moreover authority still represents the will of the Ruler of the Universe, Who, however, is now called by a new name, Dialectical Materialism.
|
||||
|
||||
The victory of the proletariat in Russia has some points in common with the victory of the feminists in some other countries. For ages, men had conceded the superior saintliness of women, and had consoled women for their inferiority by maintaining that saintliness is more desirable than power. At last the feminists decided that they would have both, since the pioneers among them believed all that the men had told them about the desirability of virtue, but not what they had told them about the worthlessness of political power. A similar thing has happened in Russia as regards manual work. For ages, the rich and their sycophants have written in praise of 'honest toil', have praised the simple life, have professed a religion which teaches that the poor are much more likely to go to heaven than the rich, and in general have tried to make manual workers believe that there is some special nobility about altering the position of matter in space, just as men tried to make women believe that they derived some special nobility from their sexual enslavement. In Russia, all this teaching about the excellence of manual work has been taken seriously, with the result that the manual worker is more honored than anyone else. What are, in essence, revivalist appeals are made, but not for the old purposes: they are made to secure shock workers for special tasks. Manual work is the ideal which is held before the young, and is the basis of all ethical teaching.
|
||||
|
||||
For the present, possibly, this is all to the good. A large country, full of natural resources, awaits development, and has has to be developed with very little use of credit. In these circumstances, hard work is necessary, and is likely to bring a great reward. But what will happen when the point has been reached where everybody could be comfortable without working long hours?
|
||||
|
||||
In the West, we have various ways of dealing with this problem. We have no attempt at economic justice, so that a large proportion of the total produce goes to a small minority of the population, many of whom do no work at all. Owing to the absence of any central control over production, we produce hosts of things that are not wanted. We keep a large percentage of the working population idle, because we can dispense with their labor by making the others overwork. When all these methods prove inadequate, we have a war: we cause a number of people to manufacture high explosives, and a number of others to explode them, as if we were children who had just discovered fireworks. By a combination of all these devices we manage, though with difficulty, to keep alive the notion that a great deal of severe manual work must be the lot of the average man.
|
||||
|
||||
In Russia, owing to more economic justice and central control over production, the problem will have to be differently solved. the rational solution would be, as soon as the necessaries and elementary comforts can be provided for all, to reduce the hours of labor gradually, allowing a popular vote to decide, at each stage, whether more leisure or more goods were to be preferred. But, having taught the supreme virtue of hard work, it is difficult to see how the authorities can aim at a paradise in which there will be much leisure and little work. It seems more likely that they will find continually fresh schemes, by which present leisure is to be sacrificed to future productivity. I read recently of an ingenious plan put forward by Russian engineers, for making the White Sea and the northern coasts of Siberia warm, by putting a dam across the Kara Sea. An admirable project, but liable to postpone proletarian comfort for a generation, while the nobility of toil is being displayed amid the ice-fields and snowstorms of the Arctic Ocean. This sort of thing, if it happens, will be the result of regarding the virtue of hard work as an end in itself, rather than as a means to a state of affairs in which it is no longer needed.
|
||||
|
||||
The fact is that moving matter about, while a certain amount of it is necessary to our existence, is emphatically not one of the ends of human life. If it were, we should have to consider every navvy superior to Shakespeare. We have been misled in this matter by two causes. One is the necessity of keeping the poor contented, which has led the rich, for thousands of years, to preach the dignity of labor, while taking care themselves to remain undignified in this respect. The other is the new pleasure in mechanism, which makes us delight in the astonishingly clever changes that we can produce on the earth's surface. Neither of these motives makes any great appeal to the actual worker. If you ask him what he thinks the best part of his life, he is not likely to say: 'I enjoy manual work because it makes me feel that I am fulfilling man's noblest task, and because I like to think how much man can transform his planet. It is true that my body demands periods of rest, which I have to fill in as best I may, but I am never so happy as when the morning comes and I can return to the toil from which my contentment springs.' I have never heard working men say this sort of thing. They consider work, as it should be considered, a necessary means to a livelihood, and it is from their leisure that they derive whatever happiness they may enjoy.
|
||||
|
||||
It will be said that, while a little leisure is pleasant, men would not know how to fill their days if they had only four hours of work out of the twenty-four. In so far as this is true in the modern world, it is a condemnation of our civilization; it would not have been true at any earlier period. There was formerly a capacity for light-heartedness and play which has been to some extent inhibited by the cult of efficiency. The modern man thinks that everything ought to be done for the sake of something else, and never for its own sake. Serious-minded persons, for example, are continually condemning the habit of going to the cinema, and telling us that it leads the young into crime. But all the work that goes to producing a cinema is respectable, because it is work, and because it brings a money profit. The notion that the desirable activities are those that bring a profit has made everything topsy-turvy. The butcher who provides you with meat and the baker who provides you with bread are praiseworthy, because they are making money; but when you enjoy the food they have provided, you are merely frivolous, unless you eat only to get strength for your work. Broadly speaking, it is held that getting money is good and spending money is bad. Seeing that they are two sides of one transaction, this is absurd; one might as well maintain that keys are good, but keyholes are bad. Whatever merit there may be in the production of goods must be entirely derivative from the advantage to be obtained by consuming them. The individual, in our society, works for profit; but the social purpose of his work lies in the consumption of what he produces. It is this divorce between the individual and the social purpose of production that makes it so difficult for men to think clearly in a world in which profit-making is the incentive to industry. We think too much of production, and too little of consumption. One result is that we attach too little importance to enjoyment and simple happiness, and that we do not judge production by the pleasure that it gives to the consumer.
|
||||
|
||||
When I suggest that working hours should be reduced to four, I am not meaning to imply that all the remaining time should necessarily be spent in pure frivolity. I mean that four hours' work a day should entitle a man to the necessities and elementary comforts of life, and that the rest of his time should be his to use as he might see fit. It is an essential part of any such social system that education should be carried further than it usually is at present, and should aim, in part, at providing tastes which would enable a man to use leisure intelligently. I am not thinking mainly of the sort of things that would be considered 'highbrow'. Peasant dances have died out except in remote rural areas, but the impulses which caused them to be cultivated must still exist in human nature. The pleasures of urban populations have become mainly passive: seeing cinemas, watching football matches, listening to the radio, and so on. This results from the fact that their active energies are fully taken up with work; if they had more leisure, they would again enjoy pleasures in which they took an active part.
|
||||
|
||||
In the past, there was a small leisure class and a larger working class. The leisure class enjoyed advantages for which there was no basis in social justice; this necessarily made it oppressive, limited its sympathies, and caused it to invent theories by which to justify its privileges. These facts greatly diminished its excellence, but in spite of this drawback it contributed nearly the whole of what we call civilization. It cultivated the arts and discovered the sciences; it wrote the books, invented the philosophies, and refined social relations. Even the liberation of the oppressed has usually been inaugurated from above. Without the leisure class, mankind would never have emerged from barbarism.
|
||||
|
||||
The method of a leisure class without duties was, however, extraordinarily wasteful. None of the members of the class had to be taught to be industrious, and the class as a whole was not exceptionally intelligent. The class might produce one Darwin, but against him had to be set tens of thousands of country gentlemen who never thought of anything more intelligent than fox-hunting and punishing poachers. At present, the universities are supposed to provide, in a more systematic way, what the leisure class provided accidentally and as a by-product. This is a great improvement, but it has certain drawbacks. University life is so different from life in the world at large that men who live in academic milieu tend to be unaware of the preoccupations and problems of ordinary men and women; moreover their ways of expressing themselves are usually such as to rob their opinions of the influence that they ought to have upon the general public. Another disadvantage is that in universities studies are organized, and the man who thinks of some original line of research is likely to be discouraged. Academic institutions, therefore, useful as they are, are not adequate guardians of the interests of civilization in a world where everyone outside their walls is too busy for unutilitarian pursuits.
|
||||
|
||||
In a world where no one is compelled to work more than four hours a day, every person possessed of scientific curiosity will be able to indulge it, and every painter will be able to paint without starving, however excellent his pictures may be. Young writers will not be obliged to draw attention to themselves by sensational pot-boilers, with a view to acquiring the economic independence needed for monumental works, for which, when the time at last comes, they will have lost the taste and capacity. Men who, in their professional work, have become interested in some phase of economics or government, will be able to develop their ideas without the academic detachment that makes the work of university economists often seem lacking in reality. Medical men will have the time to learn about the progress of medicine, teachers will not be exasperatedly struggling to teach by routine methods things which they learnt in their youth, which may, in the interval, have been proved to be untrue.
|
||||
|
||||
Above all, there will be happiness and joy of life, instead of frayed nerves, weariness, and dyspepsia. The work exacted will be enough to make leisure delightful, but not enough to produce exhaustion. Since men will not be tired in their spare time, they will not demand only such amusements as are passive and vapid. At least one per cent will probably devote the time not spent in professional work to pursuits of some public importance, and, since they will not depend upon these pursuits for their livelihood, their originality will be unhampered, and there will be no need to conform to the standards set by elderly pundits. But it is not only in these exceptional cases that the advantages of leisure will appear. Ordinary men and women, having the opportunity of a happy life, will become more kindly and less persecuting and less inclined to view others with suspicion. The taste for war will die out, partly for this reason, and partly because it will involve long and severe work for all. Good nature is, of all moral qualities, the one that the world needs most, and good nature is the result of ease and security, not of a life of arduous struggle. Modern methods of production have given us the possibility of ease and security for all; we have chosen, instead, to have overwork for some and starvation for others. Hitherto we have continued to be as energetic as we were before there were machines; in this we have been foolish, but there is no reason to go on being foolish forever.
|
||||
|
||||
[1] Since then, members of the Communist Party have succeeded to this privilege of the warriors and priests.
|
|
@ -1,31 +0,0 @@
|
|||
var assert = require('assert');
|
||||
var wordwrap = require('wordwrap');
|
||||
|
||||
var fs = require('fs');
|
||||
var idleness = fs.readFileSync(__dirname + '/idleness.txt', 'utf8');
|
||||
|
||||
exports.stop80 = function () {
|
||||
var lines = wordwrap(80)(idleness).split(/\n/);
|
||||
var words = idleness.split(/\s+/);
|
||||
|
||||
lines.forEach(function (line) {
|
||||
assert.ok(line.length <= 80, 'line > 80 columns');
|
||||
var chunks = line.match(/\S/) ? line.split(/\s+/) : [];
|
||||
assert.deepEqual(chunks, words.splice(0, chunks.length));
|
||||
});
|
||||
};
|
||||
|
||||
exports.start20stop60 = function () {
|
||||
var lines = wordwrap(20, 100)(idleness).split(/\n/);
|
||||
var words = idleness.split(/\s+/);
|
||||
|
||||
lines.forEach(function (line) {
|
||||
assert.ok(line.length <= 100, 'line > 100 columns');
|
||||
var chunks = line
|
||||
.split(/\s+/)
|
||||
.filter(function (x) { return x.match(/\S/) })
|
||||
;
|
||||
assert.deepEqual(chunks, words.splice(0, chunks.length));
|
||||
assert.deepEqual(line.slice(0, 20), new Array(20 + 1).join(' '));
|
||||
});
|
||||
};
|
File diff suppressed because one or more lines are too long
|
@ -1,487 +0,0 @@
|
|||
optimist
|
||||
========
|
||||
|
||||
Optimist is a node.js library for option parsing for people who hate option
|
||||
parsing. More specifically, this module is for people who like all the --bells
|
||||
and -whistlz of program usage but think optstrings are a waste of time.
|
||||
|
||||
With optimist, option parsing doesn't have to suck (as much).
|
||||
|
||||
[![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist)
|
||||
|
||||
examples
|
||||
========
|
||||
|
||||
With Optimist, the options are just a hash! No optstrings attached.
|
||||
-------------------------------------------------------------------
|
||||
|
||||
xup.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
|
||||
if (argv.rif - 5 * argv.xup > 7.138) {
|
||||
console.log('Buy more riffiwobbles');
|
||||
}
|
||||
else {
|
||||
console.log('Sell the xupptumblers');
|
||||
}
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./xup.js --rif=55 --xup=9.52
|
||||
Buy more riffiwobbles
|
||||
|
||||
$ ./xup.js --rif 12 --xup 8.1
|
||||
Sell the xupptumblers
|
||||
|
||||
![This one's optimistic.](http://substack.net/images/optimistic.png)
|
||||
|
||||
But wait! There's more! You can do short options:
|
||||
-------------------------------------------------
|
||||
|
||||
short.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
console.log('(%d,%d)', argv.x, argv.y);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./short.js -x 10 -y 21
|
||||
(10,21)
|
||||
|
||||
And booleans, both long and short (and grouped):
|
||||
----------------------------------
|
||||
|
||||
bool.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var util = require('util');
|
||||
var argv = require('optimist').argv;
|
||||
|
||||
if (argv.s) {
|
||||
util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');
|
||||
}
|
||||
console.log(
|
||||
(argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')
|
||||
);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./bool.js -s
|
||||
The cat says: meow
|
||||
|
||||
$ ./bool.js -sp
|
||||
The cat says: meow.
|
||||
|
||||
$ ./bool.js -sp --fr
|
||||
Le chat dit: miaou.
|
||||
|
||||
And non-hypenated options too! Just use `argv._`!
|
||||
-------------------------------------------------
|
||||
|
||||
nonopt.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
console.log('(%d,%d)', argv.x, argv.y);
|
||||
console.log(argv._);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./nonopt.js -x 6.82 -y 3.35 moo
|
||||
(6.82,3.35)
|
||||
[ 'moo' ]
|
||||
|
||||
$ ./nonopt.js foo -x 0.54 bar -y 1.12 baz
|
||||
(0.54,1.12)
|
||||
[ 'foo', 'bar', 'baz' ]
|
||||
|
||||
Plus, Optimist comes with .usage() and .demand()!
|
||||
-------------------------------------------------
|
||||
|
||||
divide.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.usage('Usage: $0 -x [num] -y [num]')
|
||||
.demand(['x','y'])
|
||||
.argv;
|
||||
|
||||
console.log(argv.x / argv.y);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./divide.js -x 55 -y 11
|
||||
5
|
||||
|
||||
$ node ./divide.js -x 4.91 -z 2.51
|
||||
Usage: node ./divide.js -x [num] -y [num]
|
||||
|
||||
Options:
|
||||
-x [required]
|
||||
-y [required]
|
||||
|
||||
Missing required arguments: y
|
||||
|
||||
EVEN MORE HOLY COW
|
||||
------------------
|
||||
|
||||
default_singles.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.default('x', 10)
|
||||
.default('y', 10)
|
||||
.argv
|
||||
;
|
||||
console.log(argv.x + argv.y);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./default_singles.js -x 5
|
||||
15
|
||||
|
||||
default_hash.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.default({ x : 10, y : 10 })
|
||||
.argv
|
||||
;
|
||||
console.log(argv.x + argv.y);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./default_hash.js -y 7
|
||||
17
|
||||
|
||||
And if you really want to get all descriptive about it...
|
||||
---------------------------------------------------------
|
||||
|
||||
boolean_single.js
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.boolean('v')
|
||||
.argv
|
||||
;
|
||||
console.dir(argv);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./boolean_single.js -v foo bar baz
|
||||
true
|
||||
[ 'bar', 'baz', 'foo' ]
|
||||
|
||||
boolean_double.js
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.boolean(['x','y','z'])
|
||||
.argv
|
||||
;
|
||||
console.dir([ argv.x, argv.y, argv.z ]);
|
||||
console.dir(argv._);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./boolean_double.js -x -z one two three
|
||||
[ true, false, true ]
|
||||
[ 'one', 'two', 'three' ]
|
||||
|
||||
Optimist is here to help...
|
||||
---------------------------
|
||||
|
||||
You can describe parameters for help messages and set aliases. Optimist figures
|
||||
out how to format a handy help string automatically.
|
||||
|
||||
line_count.js
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.usage('Count the lines in a file.\nUsage: $0')
|
||||
.demand('f')
|
||||
.alias('f', 'file')
|
||||
.describe('f', 'Load a file')
|
||||
.argv
|
||||
;
|
||||
|
||||
var fs = require('fs');
|
||||
var s = fs.createReadStream(argv.file);
|
||||
|
||||
var lines = 0;
|
||||
s.on('data', function (buf) {
|
||||
lines += buf.toString().match(/\n/g).length;
|
||||
});
|
||||
|
||||
s.on('end', function () {
|
||||
console.log(lines);
|
||||
});
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ node line_count.js
|
||||
Count the lines in a file.
|
||||
Usage: node ./line_count.js
|
||||
|
||||
Options:
|
||||
-f, --file Load a file [required]
|
||||
|
||||
Missing required arguments: f
|
||||
|
||||
$ node line_count.js --file line_count.js
|
||||
20
|
||||
|
||||
$ node line_count.js -f line_count.js
|
||||
20
|
||||
|
||||
methods
|
||||
=======
|
||||
|
||||
By itself,
|
||||
|
||||
````javascript
|
||||
require('optimist').argv
|
||||
`````
|
||||
|
||||
will use `process.argv` array to construct the `argv` object.
|
||||
|
||||
You can pass in the `process.argv` yourself:
|
||||
|
||||
````javascript
|
||||
require('optimist')([ '-x', '1', '-y', '2' ]).argv
|
||||
````
|
||||
|
||||
or use .parse() to do the same thing:
|
||||
|
||||
````javascript
|
||||
require('optimist').parse([ '-x', '1', '-y', '2' ])
|
||||
````
|
||||
|
||||
The rest of these methods below come in just before the terminating `.argv`.
|
||||
|
||||
.alias(key, alias)
|
||||
------------------
|
||||
|
||||
Set key names as equivalent such that updates to a key will propagate to aliases
|
||||
and vice-versa.
|
||||
|
||||
Optionally `.alias()` can take an object that maps keys to aliases.
|
||||
|
||||
.default(key, value)
|
||||
--------------------
|
||||
|
||||
Set `argv[key]` to `value` if no option was specified on `process.argv`.
|
||||
|
||||
Optionally `.default()` can take an object that maps keys to default values.
|
||||
|
||||
.demand(key)
|
||||
------------
|
||||
|
||||
If `key` is a string, show the usage information and exit if `key` wasn't
|
||||
specified in `process.argv`.
|
||||
|
||||
If `key` is a number, demand at least as many non-option arguments, which show
|
||||
up in `argv._`.
|
||||
|
||||
If `key` is an Array, demand each element.
|
||||
|
||||
.describe(key, desc)
|
||||
--------------------
|
||||
|
||||
Describe a `key` for the generated usage information.
|
||||
|
||||
Optionally `.describe()` can take an object that maps keys to descriptions.
|
||||
|
||||
.options(key, opt)
|
||||
------------------
|
||||
|
||||
Instead of chaining together `.alias().demand().default()`, you can specify
|
||||
keys in `opt` for each of the chainable methods.
|
||||
|
||||
For example:
|
||||
|
||||
````javascript
|
||||
var argv = require('optimist')
|
||||
.options('f', {
|
||||
alias : 'file',
|
||||
default : '/etc/passwd',
|
||||
})
|
||||
.argv
|
||||
;
|
||||
````
|
||||
|
||||
is the same as
|
||||
|
||||
````javascript
|
||||
var argv = require('optimist')
|
||||
.alias('f', 'file')
|
||||
.default('f', '/etc/passwd')
|
||||
.argv
|
||||
;
|
||||
````
|
||||
|
||||
Optionally `.options()` can take an object that maps keys to `opt` parameters.
|
||||
|
||||
.usage(message)
|
||||
---------------
|
||||
|
||||
Set a usage message to show which commands to use. Inside `message`, the string
|
||||
`$0` will get interpolated to the current script name or node command for the
|
||||
present script similar to how `$0` works in bash or perl.
|
||||
|
||||
.check(fn)
|
||||
----------
|
||||
|
||||
Check that certain conditions are met in the provided arguments.
|
||||
|
||||
If `fn` throws or returns `false`, show the thrown error, usage information, and
|
||||
exit.
|
||||
|
||||
.boolean(key)
|
||||
-------------
|
||||
|
||||
Interpret `key` as a boolean. If a non-flag option follows `key` in
|
||||
`process.argv`, that string won't get set as the value of `key`.
|
||||
|
||||
If `key` never shows up as a flag in `process.arguments`, `argv[key]` will be
|
||||
`false`.
|
||||
|
||||
If `key` is an Array, interpret all the elements as booleans.
|
||||
|
||||
.string(key)
|
||||
------------
|
||||
|
||||
Tell the parser logic not to interpret `key` as a number or boolean.
|
||||
This can be useful if you need to preserve leading zeros in an input.
|
||||
|
||||
If `key` is an Array, interpret all the elements as strings.
|
||||
|
||||
.wrap(columns)
|
||||
--------------
|
||||
|
||||
Format usage output to wrap at `columns` many columns.
|
||||
|
||||
.help()
|
||||
-------
|
||||
|
||||
Return the generated usage string.
|
||||
|
||||
.showHelp(fn=console.error)
|
||||
---------------------------
|
||||
|
||||
Print the usage data using `fn` for printing.
|
||||
|
||||
.parse(args)
|
||||
------------
|
||||
|
||||
Parse `args` instead of `process.argv`. Returns the `argv` object.
|
||||
|
||||
.argv
|
||||
-----
|
||||
|
||||
Get the arguments as a plain old object.
|
||||
|
||||
Arguments without a corresponding flag show up in the `argv._` array.
|
||||
|
||||
The script name or node command is available at `argv.$0` similarly to how `$0`
|
||||
works in bash or perl.
|
||||
|
||||
parsing tricks
|
||||
==============
|
||||
|
||||
stop parsing
|
||||
------------
|
||||
|
||||
Use `--` to stop parsing flags and stuff the remainder into `argv._`.
|
||||
|
||||
$ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4
|
||||
{ _: [ '-c', '3', '-d', '4' ],
|
||||
'$0': 'node ./examples/reflect.js',
|
||||
a: 1,
|
||||
b: 2 }
|
||||
|
||||
negate fields
|
||||
-------------
|
||||
|
||||
If you want to explicity set a field to false instead of just leaving it
|
||||
undefined or to override a default you can do `--no-key`.
|
||||
|
||||
$ node examples/reflect.js -a --no-b
|
||||
{ _: [],
|
||||
'$0': 'node ./examples/reflect.js',
|
||||
a: true,
|
||||
b: false }
|
||||
|
||||
numbers
|
||||
-------
|
||||
|
||||
Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to
|
||||
one. This way you can just `net.createConnection(argv.port)` and you can add
|
||||
numbers out of `argv` with `+` without having that mean concatenation,
|
||||
which is super frustrating.
|
||||
|
||||
duplicates
|
||||
----------
|
||||
|
||||
If you specify a flag multiple times it will get turned into an array containing
|
||||
all the values in order.
|
||||
|
||||
$ node examples/reflect.js -x 5 -x 8 -x 0
|
||||
{ _: [],
|
||||
'$0': 'node ./examples/reflect.js',
|
||||
x: [ 5, 8, 0 ] }
|
||||
|
||||
dot notation
|
||||
------------
|
||||
|
||||
When you use dots (`.`s) in argument names, an implicit object path is assumed.
|
||||
This lets you organize arguments into nested objects.
|
||||
|
||||
$ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5
|
||||
{ _: [],
|
||||
'$0': 'node ./examples/reflect.js',
|
||||
foo: { bar: { baz: 33 }, quux: 5 } }
|
||||
|
||||
installation
|
||||
============
|
||||
|
||||
With [npm](http://github.com/isaacs/npm), just do:
|
||||
npm install optimist
|
||||
|
||||
or clone this project on github:
|
||||
|
||||
git clone http://github.com/substack/node-optimist.git
|
||||
|
||||
To run the tests with [expresso](http://github.com/visionmedia/expresso),
|
||||
just do:
|
||||
|
||||
expresso
|
||||
|
||||
inspired By
|
||||
===========
|
||||
|
||||
This module is loosely inspired by Perl's
|
||||
[Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).
|
|
@ -1,71 +0,0 @@
|
|||
var spawn = require('child_process').spawn;
|
||||
var test = require('tap').test;
|
||||
|
||||
test('dotSlashEmpty', testCmd('./bin.js', []));
|
||||
|
||||
test('dotSlashArgs', testCmd('./bin.js', [ 'a', 'b', 'c' ]));
|
||||
|
||||
test('nodeEmpty', testCmd('node bin.js', []));
|
||||
|
||||
test('nodeArgs', testCmd('node bin.js', [ 'x', 'y', 'z' ]));
|
||||
|
||||
test('whichNodeEmpty', function (t) {
|
||||
var which = spawn('which', ['node']);
|
||||
|
||||
which.stdout.on('data', function (buf) {
|
||||
t.test(
|
||||
testCmd(buf.toString().trim() + ' bin.js', [])
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
which.stderr.on('data', function (err) {
|
||||
assert.error(err);
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
test('whichNodeArgs', function (t) {
|
||||
var which = spawn('which', ['node']);
|
||||
|
||||
which.stdout.on('data', function (buf) {
|
||||
t.test(
|
||||
testCmd(buf.toString().trim() + ' bin.js', [ 'q', 'r' ])
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
which.stderr.on('data', function (err) {
|
||||
t.error(err);
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
function testCmd (cmd, args) {
|
||||
|
||||
return function (t) {
|
||||
var to = setTimeout(function () {
|
||||
assert.fail('Never got stdout data.')
|
||||
}, 5000);
|
||||
|
||||
var oldDir = process.cwd();
|
||||
process.chdir(__dirname + '/_');
|
||||
|
||||
var cmds = cmd.split(' ');
|
||||
|
||||
var bin = spawn(cmds[0], cmds.slice(1).concat(args.map(String)));
|
||||
process.chdir(oldDir);
|
||||
|
||||
bin.stderr.on('data', function (err) {
|
||||
t.error(err);
|
||||
t.end();
|
||||
});
|
||||
|
||||
bin.stdout.on('data', function (buf) {
|
||||
clearTimeout(to);
|
||||
var _ = JSON.parse(buf.toString());
|
||||
t.same(_.map(String), args.map(String));
|
||||
t.end();
|
||||
});
|
||||
};
|
||||
}
|
|
@ -1,2 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
console.log(JSON.stringify(process.argv));
|
|
@ -1,3 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('../../index').argv
|
||||
console.log(JSON.stringify(argv._));
|
|
@ -1,446 +0,0 @@
|
|||
var optimist = require('../index');
|
||||
var path = require('path');
|
||||
var test = require('tap').test;
|
||||
|
||||
var $0 = 'node ./' + path.relative(process.cwd(), __filename);
|
||||
|
||||
test('short boolean', function (t) {
|
||||
var parse = optimist.parse([ '-b' ]);
|
||||
t.same(parse, { b : true, _ : [], $0 : $0 });
|
||||
t.same(typeof parse.b, 'boolean');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('long boolean', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--bool' ]),
|
||||
{ bool : true, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('bare', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ 'foo', 'bar', 'baz' ]),
|
||||
{ _ : [ 'foo', 'bar', 'baz' ], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('short group', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-cats' ]),
|
||||
{ c : true, a : true, t : true, s : true, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('short group next', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-cats', 'meow' ]),
|
||||
{ c : true, a : true, t : true, s : 'meow', _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('short capture', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-h', 'localhost' ]),
|
||||
{ h : 'localhost', _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('short captures', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-h', 'localhost', '-p', '555' ]),
|
||||
{ h : 'localhost', p : 555, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('long capture sp', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--pow', 'xixxle' ]),
|
||||
{ pow : 'xixxle', _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('long capture eq', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--pow=xixxle' ]),
|
||||
{ pow : 'xixxle', _ : [], $0 : $0 }
|
||||
);
|
||||
t.end()
|
||||
});
|
||||
|
||||
test('long captures sp', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--host', 'localhost', '--port', '555' ]),
|
||||
{ host : 'localhost', port : 555, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('long captures eq', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--host=localhost', '--port=555' ]),
|
||||
{ host : 'localhost', port : 555, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('mixed short bool and capture', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
|
||||
{
|
||||
f : true, p : 555, h : 'localhost',
|
||||
_ : [ 'script.js' ], $0 : $0,
|
||||
}
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('short and long', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
|
||||
{
|
||||
f : true, p : 555, h : 'localhost',
|
||||
_ : [ 'script.js' ], $0 : $0,
|
||||
}
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('no', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--no-moo' ]),
|
||||
{ moo : false, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('multi', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]),
|
||||
{ v : ['a','b','c'], _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('comprehensive', function (t) {
|
||||
t.same(
|
||||
optimist.parse([
|
||||
'--name=meowmers', 'bare', '-cats', 'woo',
|
||||
'-h', 'awesome', '--multi=quux',
|
||||
'--key', 'value',
|
||||
'-b', '--bool', '--no-meep', '--multi=baz',
|
||||
'--', '--not-a-flag', 'eek'
|
||||
]),
|
||||
{
|
||||
c : true,
|
||||
a : true,
|
||||
t : true,
|
||||
s : 'woo',
|
||||
h : 'awesome',
|
||||
b : true,
|
||||
bool : true,
|
||||
key : 'value',
|
||||
multi : [ 'quux', 'baz' ],
|
||||
meep : false,
|
||||
name : 'meowmers',
|
||||
_ : [ 'bare', '--not-a-flag', 'eek' ],
|
||||
$0 : $0
|
||||
}
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('nums', function (t) {
|
||||
var argv = optimist.parse([
|
||||
'-x', '1234',
|
||||
'-y', '5.67',
|
||||
'-z', '1e7',
|
||||
'-w', '10f',
|
||||
'--hex', '0xdeadbeef',
|
||||
'789',
|
||||
]);
|
||||
t.same(argv, {
|
||||
x : 1234,
|
||||
y : 5.67,
|
||||
z : 1e7,
|
||||
w : '10f',
|
||||
hex : 0xdeadbeef,
|
||||
_ : [ 789 ],
|
||||
$0 : $0
|
||||
});
|
||||
t.same(typeof argv.x, 'number');
|
||||
t.same(typeof argv.y, 'number');
|
||||
t.same(typeof argv.z, 'number');
|
||||
t.same(typeof argv.w, 'string');
|
||||
t.same(typeof argv.hex, 'number');
|
||||
t.same(typeof argv._[0], 'number');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('flag boolean', function (t) {
|
||||
var parse = optimist([ '-t', 'moo' ]).boolean(['t']).argv;
|
||||
t.same(parse, { t : true, _ : [ 'moo' ], $0 : $0 });
|
||||
t.same(typeof parse.t, 'boolean');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('flag boolean value', function (t) {
|
||||
var parse = optimist(['--verbose', 'false', 'moo', '-t', 'true'])
|
||||
.boolean(['t', 'verbose']).default('verbose', true).argv;
|
||||
|
||||
t.same(parse, {
|
||||
verbose: false,
|
||||
t: true,
|
||||
_: ['moo'],
|
||||
$0 : $0
|
||||
});
|
||||
|
||||
t.same(typeof parse.verbose, 'boolean');
|
||||
t.same(typeof parse.t, 'boolean');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('flag boolean default false', function (t) {
|
||||
var parse = optimist(['moo'])
|
||||
.boolean(['t', 'verbose'])
|
||||
.default('verbose', false)
|
||||
.default('t', false).argv;
|
||||
|
||||
t.same(parse, {
|
||||
verbose: false,
|
||||
t: false,
|
||||
_: ['moo'],
|
||||
$0 : $0
|
||||
});
|
||||
|
||||
t.same(typeof parse.verbose, 'boolean');
|
||||
t.same(typeof parse.t, 'boolean');
|
||||
t.end();
|
||||
|
||||
});
|
||||
|
||||
test('boolean groups', function (t) {
|
||||
var parse = optimist([ '-x', '-z', 'one', 'two', 'three' ])
|
||||
.boolean(['x','y','z']).argv;
|
||||
|
||||
t.same(parse, {
|
||||
x : true,
|
||||
y : false,
|
||||
z : true,
|
||||
_ : [ 'one', 'two', 'three' ],
|
||||
$0 : $0
|
||||
});
|
||||
|
||||
t.same(typeof parse.x, 'boolean');
|
||||
t.same(typeof parse.y, 'boolean');
|
||||
t.same(typeof parse.z, 'boolean');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('newlines in params' , function (t) {
|
||||
var args = optimist.parse([ '-s', "X\nX" ])
|
||||
t.same(args, { _ : [], s : "X\nX", $0 : $0 });
|
||||
|
||||
// reproduce in bash:
|
||||
// VALUE="new
|
||||
// line"
|
||||
// node program.js --s="$VALUE"
|
||||
args = optimist.parse([ "--s=X\nX" ])
|
||||
t.same(args, { _ : [], s : "X\nX", $0 : $0 });
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('strings' , function (t) {
|
||||
var s = optimist([ '-s', '0001234' ]).string('s').argv.s;
|
||||
t.same(s, '0001234');
|
||||
t.same(typeof s, 'string');
|
||||
|
||||
var x = optimist([ '-x', '56' ]).string('x').argv.x;
|
||||
t.same(x, '56');
|
||||
t.same(typeof x, 'string');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('stringArgs', function (t) {
|
||||
var s = optimist([ ' ', ' ' ]).string('_').argv._;
|
||||
t.same(s.length, 2);
|
||||
t.same(typeof s[0], 'string');
|
||||
t.same(s[0], ' ');
|
||||
t.same(typeof s[1], 'string');
|
||||
t.same(s[1], ' ');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('slashBreak', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-I/foo/bar/baz' ]),
|
||||
{ I : '/foo/bar/baz', _ : [], $0 : $0 }
|
||||
);
|
||||
t.same(
|
||||
optimist.parse([ '-xyz/foo/bar/baz' ]),
|
||||
{ x : true, y : true, z : '/foo/bar/baz', _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('alias', function (t) {
|
||||
var argv = optimist([ '-f', '11', '--zoom', '55' ])
|
||||
.alias('z', 'zoom')
|
||||
.argv
|
||||
;
|
||||
t.equal(argv.zoom, 55);
|
||||
t.equal(argv.z, argv.zoom);
|
||||
t.equal(argv.f, 11);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('multiAlias', function (t) {
|
||||
var argv = optimist([ '-f', '11', '--zoom', '55' ])
|
||||
.alias('z', [ 'zm', 'zoom' ])
|
||||
.argv
|
||||
;
|
||||
t.equal(argv.zoom, 55);
|
||||
t.equal(argv.z, argv.zoom);
|
||||
t.equal(argv.z, argv.zm);
|
||||
t.equal(argv.f, 11);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('boolean default true', function (t) {
|
||||
var argv = optimist.options({
|
||||
sometrue: {
|
||||
boolean: true,
|
||||
default: true
|
||||
}
|
||||
}).argv;
|
||||
|
||||
t.equal(argv.sometrue, true);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('boolean default false', function (t) {
|
||||
var argv = optimist.options({
|
||||
somefalse: {
|
||||
boolean: true,
|
||||
default: false
|
||||
}
|
||||
}).argv;
|
||||
|
||||
t.equal(argv.somefalse, false);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('nested dotted objects', function (t) {
|
||||
var argv = optimist([
|
||||
'--foo.bar', '3', '--foo.baz', '4',
|
||||
'--foo.quux.quibble', '5', '--foo.quux.o_O',
|
||||
'--beep.boop'
|
||||
]).argv;
|
||||
|
||||
t.same(argv.foo, {
|
||||
bar : 3,
|
||||
baz : 4,
|
||||
quux : {
|
||||
quibble : 5,
|
||||
o_O : true
|
||||
},
|
||||
});
|
||||
t.same(argv.beep, { boop : true });
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('boolean and alias with chainable api', function (t) {
|
||||
var aliased = [ '-h', 'derp' ];
|
||||
var regular = [ '--herp', 'derp' ];
|
||||
var opts = {
|
||||
herp: { alias: 'h', boolean: true }
|
||||
};
|
||||
var aliasedArgv = optimist(aliased)
|
||||
.boolean('herp')
|
||||
.alias('h', 'herp')
|
||||
.argv;
|
||||
var propertyArgv = optimist(regular)
|
||||
.boolean('herp')
|
||||
.alias('h', 'herp')
|
||||
.argv;
|
||||
var expected = {
|
||||
herp: true,
|
||||
h: true,
|
||||
'_': [ 'derp' ],
|
||||
'$0': $0,
|
||||
};
|
||||
|
||||
t.same(aliasedArgv, expected);
|
||||
t.same(propertyArgv, expected);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('boolean and alias with options hash', function (t) {
|
||||
var aliased = [ '-h', 'derp' ];
|
||||
var regular = [ '--herp', 'derp' ];
|
||||
var opts = {
|
||||
herp: { alias: 'h', boolean: true }
|
||||
};
|
||||
var aliasedArgv = optimist(aliased)
|
||||
.options(opts)
|
||||
.argv;
|
||||
var propertyArgv = optimist(regular).options(opts).argv;
|
||||
var expected = {
|
||||
herp: true,
|
||||
h: true,
|
||||
'_': [ 'derp' ],
|
||||
'$0': $0,
|
||||
};
|
||||
|
||||
t.same(aliasedArgv, expected);
|
||||
t.same(propertyArgv, expected);
|
||||
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('boolean and alias using explicit true', function (t) {
|
||||
var aliased = [ '-h', 'true' ];
|
||||
var regular = [ '--herp', 'true' ];
|
||||
var opts = {
|
||||
herp: { alias: 'h', boolean: true }
|
||||
};
|
||||
var aliasedArgv = optimist(aliased)
|
||||
.boolean('h')
|
||||
.alias('h', 'herp')
|
||||
.argv;
|
||||
var propertyArgv = optimist(regular)
|
||||
.boolean('h')
|
||||
.alias('h', 'herp')
|
||||
.argv;
|
||||
var expected = {
|
||||
herp: true,
|
||||
h: true,
|
||||
'_': [ ],
|
||||
'$0': $0,
|
||||
};
|
||||
|
||||
t.same(aliasedArgv, expected);
|
||||
t.same(propertyArgv, expected);
|
||||
t.end();
|
||||
});
|
||||
|
||||
// regression, see https://github.com/substack/node-optimist/issues/71
|
||||
test('boolean and --x=true', function(t) {
|
||||
var parsed = optimist(['--boool', '--other=true']).boolean('boool').argv;
|
||||
|
||||
t.same(parsed.boool, true);
|
||||
t.same(parsed.other, 'true');
|
||||
|
||||
parsed = optimist(['--boool', '--other=false']).boolean('boool').argv;
|
||||
|
||||
t.same(parsed.boool, true);
|
||||
t.same(parsed.other, 'false');
|
||||
t.end();
|
||||
});
|
|
@ -1,292 +0,0 @@
|
|||
var Hash = require('hashish');
|
||||
var optimist = require('../index');
|
||||
var test = require('tap').test;
|
||||
|
||||
test('usageFail', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -z 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.demand(['x','y'])
|
||||
.argv;
|
||||
});
|
||||
t.same(
|
||||
r.result,
|
||||
{ x : 10, z : 20, _ : [], $0 : './usage' }
|
||||
);
|
||||
|
||||
t.same(
|
||||
r.errors.join('\n').split(/\n+/),
|
||||
[
|
||||
'Usage: ./usage -x NUM -y NUM',
|
||||
'Options:',
|
||||
' -x [required]',
|
||||
' -y [required]',
|
||||
'Missing required arguments: y',
|
||||
]
|
||||
);
|
||||
t.same(r.logs, []);
|
||||
t.ok(r.exit);
|
||||
t.end();
|
||||
});
|
||||
|
||||
|
||||
test('usagePass', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -y 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.demand(['x','y'])
|
||||
.argv;
|
||||
});
|
||||
t.same(r, {
|
||||
result : { x : 10, y : 20, _ : [], $0 : './usage' },
|
||||
errors : [],
|
||||
logs : [],
|
||||
exit : false,
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('checkPass', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -y 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.check(function (argv) {
|
||||
if (!('x' in argv)) throw 'You forgot about -x';
|
||||
if (!('y' in argv)) throw 'You forgot about -y';
|
||||
})
|
||||
.argv;
|
||||
});
|
||||
t.same(r, {
|
||||
result : { x : 10, y : 20, _ : [], $0 : './usage' },
|
||||
errors : [],
|
||||
logs : [],
|
||||
exit : false,
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('checkFail', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -z 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.check(function (argv) {
|
||||
if (!('x' in argv)) throw 'You forgot about -x';
|
||||
if (!('y' in argv)) throw 'You forgot about -y';
|
||||
})
|
||||
.argv;
|
||||
});
|
||||
|
||||
t.same(
|
||||
r.result,
|
||||
{ x : 10, z : 20, _ : [], $0 : './usage' }
|
||||
);
|
||||
|
||||
t.same(
|
||||
r.errors.join('\n').split(/\n+/),
|
||||
[
|
||||
'Usage: ./usage -x NUM -y NUM',
|
||||
'You forgot about -y'
|
||||
]
|
||||
);
|
||||
|
||||
t.same(r.logs, []);
|
||||
t.ok(r.exit);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('checkCondPass', function (t) {
|
||||
function checker (argv) {
|
||||
return 'x' in argv && 'y' in argv;
|
||||
}
|
||||
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -y 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.check(checker)
|
||||
.argv;
|
||||
});
|
||||
t.same(r, {
|
||||
result : { x : 10, y : 20, _ : [], $0 : './usage' },
|
||||
errors : [],
|
||||
logs : [],
|
||||
exit : false,
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('checkCondFail', function (t) {
|
||||
function checker (argv) {
|
||||
return 'x' in argv && 'y' in argv;
|
||||
}
|
||||
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -z 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.check(checker)
|
||||
.argv;
|
||||
});
|
||||
|
||||
t.same(
|
||||
r.result,
|
||||
{ x : 10, z : 20, _ : [], $0 : './usage' }
|
||||
);
|
||||
|
||||
t.same(
|
||||
r.errors.join('\n').split(/\n+/).join('\n'),
|
||||
'Usage: ./usage -x NUM -y NUM\n'
|
||||
+ 'Argument check failed: ' + checker.toString()
|
||||
);
|
||||
|
||||
t.same(r.logs, []);
|
||||
t.ok(r.exit);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('countPass', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('1 2 3 --moo'.split(' '))
|
||||
.usage('Usage: $0 [x] [y] [z] {OPTIONS}')
|
||||
.demand(3)
|
||||
.argv;
|
||||
});
|
||||
t.same(r, {
|
||||
result : { _ : [ '1', '2', '3' ], moo : true, $0 : './usage' },
|
||||
errors : [],
|
||||
logs : [],
|
||||
exit : false,
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('countFail', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('1 2 --moo'.split(' '))
|
||||
.usage('Usage: $0 [x] [y] [z] {OPTIONS}')
|
||||
.demand(3)
|
||||
.argv;
|
||||
});
|
||||
t.same(
|
||||
r.result,
|
||||
{ _ : [ '1', '2' ], moo : true, $0 : './usage' }
|
||||
);
|
||||
|
||||
t.same(
|
||||
r.errors.join('\n').split(/\n+/),
|
||||
[
|
||||
'Usage: ./usage [x] [y] [z] {OPTIONS}',
|
||||
'Not enough non-option arguments: got 2, need at least 3',
|
||||
]
|
||||
);
|
||||
|
||||
t.same(r.logs, []);
|
||||
t.ok(r.exit);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('defaultSingles', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('--foo 50 --baz 70 --powsy'.split(' '))
|
||||
.default('foo', 5)
|
||||
.default('bar', 6)
|
||||
.default('baz', 7)
|
||||
.argv
|
||||
;
|
||||
});
|
||||
t.same(r.result, {
|
||||
foo : '50',
|
||||
bar : 6,
|
||||
baz : '70',
|
||||
powsy : true,
|
||||
_ : [],
|
||||
$0 : './usage',
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('defaultAliases', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('')
|
||||
.alias('f', 'foo')
|
||||
.default('f', 5)
|
||||
.argv
|
||||
;
|
||||
});
|
||||
t.same(r.result, {
|
||||
f : '5',
|
||||
foo : '5',
|
||||
_ : [],
|
||||
$0 : './usage',
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('defaultHash', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('--foo 50 --baz 70'.split(' '))
|
||||
.default({ foo : 10, bar : 20, quux : 30 })
|
||||
.argv
|
||||
;
|
||||
});
|
||||
t.same(r.result, {
|
||||
_ : [],
|
||||
$0 : './usage',
|
||||
foo : 50,
|
||||
baz : 70,
|
||||
bar : 20,
|
||||
quux : 30,
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('rebase', function (t) {
|
||||
t.equal(
|
||||
optimist.rebase('/home/substack', '/home/substack/foo/bar/baz'),
|
||||
'./foo/bar/baz'
|
||||
);
|
||||
t.equal(
|
||||
optimist.rebase('/home/substack/foo/bar/baz', '/home/substack'),
|
||||
'../../..'
|
||||
);
|
||||
t.equal(
|
||||
optimist.rebase('/home/substack/foo', '/home/substack/pow/zoom.txt'),
|
||||
'../pow/zoom.txt'
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
function checkUsage (f) {
|
||||
|
||||
var exit = false;
|
||||
|
||||
process._exit = process.exit;
|
||||
process._env = process.env;
|
||||
process._argv = process.argv;
|
||||
|
||||
process.exit = function (t) { exit = true };
|
||||
process.env = Hash.merge(process.env, { _ : 'node' });
|
||||
process.argv = [ './usage' ];
|
||||
|
||||
var errors = [];
|
||||
var logs = [];
|
||||
|
||||
console._error = console.error;
|
||||
console.error = function (msg) { errors.push(msg) };
|
||||
console._log = console.log;
|
||||
console.log = function (msg) { logs.push(msg) };
|
||||
|
||||
var result = f();
|
||||
|
||||
process.exit = process._exit;
|
||||
process.env = process._env;
|
||||
process.argv = process._argv;
|
||||
|
||||
console.error = console._error;
|
||||
console.log = console._log;
|
||||
|
||||
return {
|
||||
errors : errors,
|
||||
logs : logs,
|
||||
exit : exit,
|
||||
result : result,
|
||||
};
|
||||
};
|
|
@ -1,2 +0,0 @@
|
|||
dist/*
|
||||
node_modules/*
|
|
@ -1,4 +0,0 @@
|
|||
language: node_js
|
||||
node_js:
|
||||
- 0.8
|
||||
- "0.10"
|
|
@ -1,58 +0,0 @@
|
|||
# Change Log
|
||||
|
||||
## 0.1.22
|
||||
|
||||
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
|
||||
|
||||
## 0.1.21
|
||||
|
||||
* Fixed handling of sources that start with a slash so that they are relative to
|
||||
the source root's host.
|
||||
|
||||
## 0.1.20
|
||||
|
||||
* Fixed github issue #43: absolute URLs aren't joined with the source root
|
||||
anymore.
|
||||
|
||||
## 0.1.19
|
||||
|
||||
* Using Travis CI to run tests.
|
||||
|
||||
## 0.1.18
|
||||
|
||||
* Fixed a bug in the handling of sourceRoot.
|
||||
|
||||
## 0.1.17
|
||||
|
||||
* Added SourceNode.fromStringWithSourceMap.
|
||||
|
||||
## 0.1.16
|
||||
|
||||
* Added missing documentation.
|
||||
|
||||
* Fixed the generating of empty mappings in SourceNode.
|
||||
|
||||
## 0.1.15
|
||||
|
||||
* Added SourceMapGenerator.applySourceMap.
|
||||
|
||||
## 0.1.14
|
||||
|
||||
* The sourceRoot is now handled consistently.
|
||||
|
||||
## 0.1.13
|
||||
|
||||
* Added SourceMapGenerator.fromSourceMap.
|
||||
|
||||
## 0.1.12
|
||||
|
||||
* SourceNode now generates empty mappings too.
|
||||
|
||||
## 0.1.11
|
||||
|
||||
* Added name support to SourceNode.
|
||||
|
||||
## 0.1.10
|
||||
|
||||
* Added sourcesContent support to the customer and generator.
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
|
||||
Copyright (c) 2009-2011, Mozilla Foundation and contributors
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the names of the Mozilla Foundation nor the names of project
|
||||
contributors may be used to endorse or promote products derived from this
|
||||
software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@ -1,166 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
var copy = require('dryice').copy;
|
||||
|
||||
function removeAmdefine(src) {
|
||||
src = String(src).replace(
|
||||
/if\s*\(typeof\s*define\s*!==\s*'function'\)\s*{\s*var\s*define\s*=\s*require\('amdefine'\)\(module\);\s*}\s*/g,
|
||||
'');
|
||||
src = src.replace(
|
||||
/\b(define\(.*)('amdefine',?)/gm,
|
||||
'$1');
|
||||
return src;
|
||||
}
|
||||
removeAmdefine.onRead = true;
|
||||
|
||||
function makeNonRelative(src) {
|
||||
return src
|
||||
.replace(/require\('.\//g, 'require(\'source-map/')
|
||||
.replace(/\.\.\/\.\.\/lib\//g, '');
|
||||
}
|
||||
makeNonRelative.onRead = true;
|
||||
|
||||
function buildBrowser() {
|
||||
console.log('\nCreating dist/source-map.js');
|
||||
|
||||
var project = copy.createCommonJsProject({
|
||||
roots: [ path.join(__dirname, 'lib') ]
|
||||
});
|
||||
|
||||
copy({
|
||||
source: [
|
||||
'build/mini-require.js',
|
||||
{
|
||||
project: project,
|
||||
require: [ 'source-map/source-map-generator',
|
||||
'source-map/source-map-consumer',
|
||||
'source-map/source-node']
|
||||
},
|
||||
'build/suffix-browser.js'
|
||||
],
|
||||
filter: [
|
||||
copy.filter.moduleDefines,
|
||||
removeAmdefine
|
||||
],
|
||||
dest: 'dist/source-map.js'
|
||||
});
|
||||
}
|
||||
|
||||
function buildBrowserMin() {
|
||||
console.log('\nCreating dist/source-map.min.js');
|
||||
|
||||
copy({
|
||||
source: 'dist/source-map.js',
|
||||
filter: copy.filter.uglifyjs,
|
||||
dest: 'dist/source-map.min.js'
|
||||
});
|
||||
}
|
||||
|
||||
function buildFirefox() {
|
||||
console.log('\nCreating dist/SourceMap.jsm');
|
||||
|
||||
var project = copy.createCommonJsProject({
|
||||
roots: [ path.join(__dirname, 'lib') ]
|
||||
});
|
||||
|
||||
copy({
|
||||
source: [
|
||||
'build/prefix-source-map.jsm',
|
||||
{
|
||||
project: project,
|
||||
require: [ 'source-map/source-map-consumer',
|
||||
'source-map/source-map-generator',
|
||||
'source-map/source-node' ]
|
||||
},
|
||||
'build/suffix-source-map.jsm'
|
||||
],
|
||||
filter: [
|
||||
copy.filter.moduleDefines,
|
||||
removeAmdefine,
|
||||
makeNonRelative
|
||||
],
|
||||
dest: 'dist/SourceMap.jsm'
|
||||
});
|
||||
|
||||
// Create dist/test/Utils.jsm
|
||||
console.log('\nCreating dist/test/Utils.jsm');
|
||||
|
||||
project = copy.createCommonJsProject({
|
||||
roots: [ __dirname, path.join(__dirname, 'lib') ]
|
||||
});
|
||||
|
||||
copy({
|
||||
source: [
|
||||
'build/prefix-utils.jsm',
|
||||
'build/assert-shim.js',
|
||||
{
|
||||
project: project,
|
||||
require: [ 'test/source-map/util' ]
|
||||
},
|
||||
'build/suffix-utils.jsm'
|
||||
],
|
||||
filter: [
|
||||
copy.filter.moduleDefines,
|
||||
removeAmdefine,
|
||||
makeNonRelative
|
||||
],
|
||||
dest: 'dist/test/Utils.jsm'
|
||||
});
|
||||
|
||||
function isTestFile(f) {
|
||||
return /^test\-.*?\.js/.test(f);
|
||||
}
|
||||
|
||||
var testFiles = fs.readdirSync(path.join(__dirname, 'test', 'source-map')).filter(isTestFile);
|
||||
|
||||
testFiles.forEach(function (testFile) {
|
||||
console.log('\nCreating', path.join('dist', 'test', testFile.replace(/\-/g, '_')));
|
||||
|
||||
copy({
|
||||
source: [
|
||||
'build/test-prefix.js',
|
||||
path.join('test', 'source-map', testFile),
|
||||
'build/test-suffix.js'
|
||||
],
|
||||
filter: [
|
||||
removeAmdefine,
|
||||
makeNonRelative,
|
||||
function (input, source) {
|
||||
return input.replace('define(',
|
||||
'define("'
|
||||
+ path.join('test', 'source-map', testFile.replace(/\.js$/, ''))
|
||||
+ '", ["require", "exports", "module"], ');
|
||||
},
|
||||
function (input, source) {
|
||||
return input.replace('{THIS_MODULE}', function () {
|
||||
return "test/source-map/" + testFile.replace(/\.js$/, '');
|
||||
});
|
||||
}
|
||||
],
|
||||
dest: path.join('dist', 'test', testFile.replace(/\-/g, '_'))
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function ensureDir(name) {
|
||||
var dirExists = false;
|
||||
try {
|
||||
dirExists = fs.statSync(name).isDirectory();
|
||||
} catch (err) {}
|
||||
|
||||
if (!dirExists) {
|
||||
fs.mkdirSync(name, 0777);
|
||||
}
|
||||
}
|
||||
|
||||
ensureDir("dist");
|
||||
ensureDir("dist/test");
|
||||
buildFirefox();
|
||||
buildBrowser();
|
||||
buildBrowserMin();
|
|
@ -1,347 +0,0 @@
|
|||
# Source Map
|
||||
|
||||
This is a library to generate and consume the source map format
|
||||
[described here][format].
|
||||
|
||||
[Learn more here][feature].
|
||||
|
||||
This library was written in the Asynchronous Module Definition
|
||||
format. It should work in the following environments:
|
||||
|
||||
* Modern Browsers (either after the build, or with an AMD loader such as
|
||||
RequireJS)
|
||||
|
||||
* Inside Firefox (as a JSM file, after the build)
|
||||
|
||||
* With NodeJS versions 0.8.X and higher
|
||||
|
||||
## Installing with NPM (for use with NodeJS)
|
||||
|
||||
Simply
|
||||
|
||||
$ npm install source-map
|
||||
|
||||
Or, if you'd like to hack on this library and have it installed via npm so you
|
||||
can try out your changes:
|
||||
|
||||
$ git clone https://fitzgen@github.com/mozilla/source-map.git
|
||||
$ cd source-map
|
||||
$ npm link .
|
||||
|
||||
## Building from Source (for everywhere else)
|
||||
|
||||
Install Node and then run
|
||||
|
||||
$ git clone https://fitzgen@github.com/mozilla/source-map.git
|
||||
$ cd source-map
|
||||
$ npm link .
|
||||
|
||||
Next, run
|
||||
|
||||
$ node Makefile.dryice.js`
|
||||
|
||||
This should create the following files:
|
||||
|
||||
* `dist/source-map.js` - The unminified browser version.
|
||||
|
||||
* `dist/source-map.min.js` - The minified browser version.
|
||||
|
||||
* `dist/SourceMap.jsm` - The JavaScript Module for inclusion in Firefox
|
||||
source.
|
||||
|
||||
## API
|
||||
|
||||
Get a reference to the module:
|
||||
|
||||
// NodeJS
|
||||
var sourceMap = require('source-map');
|
||||
|
||||
// Browser builds
|
||||
var sourceMap = window.sourceMap;
|
||||
|
||||
// Inside Firefox
|
||||
let sourceMap = {};
|
||||
Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap);
|
||||
|
||||
### SourceMapConsumer
|
||||
|
||||
A SourceMapConsumer instance represents a parsed source map which we can query
|
||||
for information about the original file positions by giving it a file position
|
||||
in the generated source.
|
||||
|
||||
#### new SourceMapConsumer(rawSourceMap)
|
||||
|
||||
The only parameter is the raw source map (either as a string which can be
|
||||
`JSON.parse`'d, or an object). According to the spec, source maps have the
|
||||
following attributes:
|
||||
|
||||
* `version`: Which version of the source map spec this map is following.
|
||||
|
||||
* `sources`: An array of URLs to the original source files.
|
||||
|
||||
* `names`: An array of identifiers which can be referrenced by individual
|
||||
mappings.
|
||||
|
||||
* `sourceRoot`: Optional. The URL root from which all sources are relative.
|
||||
|
||||
* `sourcesContent`: Optional. An array of contents of the original source files.
|
||||
|
||||
* `mappings`: A string of base64 VLQs which contain the actual mappings.
|
||||
|
||||
* `file`: The generated filename this source map is associated with.
|
||||
|
||||
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
|
||||
|
||||
Returns the original source, line, and column information for the generated
|
||||
source's line and column positions provided. The only argument is an object with
|
||||
the following properties:
|
||||
|
||||
* `line`: The line number in the generated source.
|
||||
|
||||
* `column`: The column number in the generated source.
|
||||
|
||||
and an object is returned with the following properties:
|
||||
|
||||
* `source`: The original source file, or null if this information is not
|
||||
available.
|
||||
|
||||
* `line`: The line number in the original source, or null if this information is
|
||||
not available.
|
||||
|
||||
* `column`: The column number in the original source, or null or null if this
|
||||
information is not available.
|
||||
|
||||
* `name`: The original identifier, or null if this information is not available.
|
||||
|
||||
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
|
||||
|
||||
Returns the generated line and column information for the original source,
|
||||
line, and column positions provided. The only argument is an object with
|
||||
the following properties:
|
||||
|
||||
* `source`: The filename of the original source.
|
||||
|
||||
* `line`: The line number in the original source.
|
||||
|
||||
* `column`: The column number in the original source.
|
||||
|
||||
and an object is returned with the following properties:
|
||||
|
||||
* `line`: The line number in the generated source, or null.
|
||||
|
||||
* `column`: The column number in the generated source, or null.
|
||||
|
||||
#### SourceMapConsumer.prototype.sourceContentFor(source)
|
||||
|
||||
Returns the original source content for the source provided. The only
|
||||
argument is the URL of the original source file.
|
||||
|
||||
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
|
||||
|
||||
Iterate over each mapping between an original source/line/column and a
|
||||
generated line/column in this source map.
|
||||
|
||||
* `callback`: The function that is called with each mapping.
|
||||
|
||||
* `context`: Optional. If specified, this object will be the value of `this`
|
||||
every time that `callback` is called.
|
||||
|
||||
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
|
||||
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
|
||||
the mappings sorted by the generated file's line/column order or the
|
||||
original's source/line/column order, respectively. Defaults to
|
||||
`SourceMapConsumer.GENERATED_ORDER`.
|
||||
|
||||
### SourceMapGenerator
|
||||
|
||||
An instance of the SourceMapGenerator represents a source map which is being
|
||||
built incrementally.
|
||||
|
||||
#### new SourceMapGenerator(startOfSourceMap)
|
||||
|
||||
To create a new one, you must pass an object with the following properties:
|
||||
|
||||
* `file`: The filename of the generated source that this source map is
|
||||
associated with.
|
||||
|
||||
* `sourceRoot`: An optional root for all relative URLs in this source map.
|
||||
|
||||
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
|
||||
|
||||
Creates a new SourceMapGenerator based on a SourceMapConsumer
|
||||
|
||||
* `sourceMapConsumer` The SourceMap.
|
||||
|
||||
#### SourceMapGenerator.prototype.addMapping(mapping)
|
||||
|
||||
Add a single mapping from original source line and column to the generated
|
||||
source's line and column for this source map being created. The mapping object
|
||||
should have the following properties:
|
||||
|
||||
* `generated`: An object with the generated line and column positions.
|
||||
|
||||
* `original`: An object with the original line and column positions.
|
||||
|
||||
* `source`: The original source file (relative to the sourceRoot).
|
||||
|
||||
* `name`: An optional original token name for this mapping.
|
||||
|
||||
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
|
||||
|
||||
Set the source content for an original source file.
|
||||
|
||||
* `sourceFile` the URL of the original source file.
|
||||
|
||||
* `sourceContent` the content of the source file.
|
||||
|
||||
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile])
|
||||
|
||||
Applies a SourceMap for a source file to the SourceMap.
|
||||
Each mapping to the supplied source file is rewritten using the
|
||||
supplied SourceMap. Note: The resolution for the resulting mappings
|
||||
is the minimium of this map and the supplied map.
|
||||
|
||||
* `sourceMapConsumer`: The SourceMap to be applied.
|
||||
|
||||
* `sourceFile`: Optional. The filename of the source file.
|
||||
If omitted, sourceMapConsumer.file will be used.
|
||||
|
||||
#### SourceMapGenerator.prototype.toString()
|
||||
|
||||
Renders the source map being generated to a string.
|
||||
|
||||
### SourceNode
|
||||
|
||||
SourceNodes provide a way to abstract over interpolating and/or concatenating
|
||||
snippets of generated JavaScript source code, while maintaining the line and
|
||||
column information associated between those snippets and the original source
|
||||
code. This is useful as the final intermediate representation a compiler might
|
||||
use before outputting the generated JS and source map.
|
||||
|
||||
#### new SourceNode(line, column, source[, chunk[, name]])
|
||||
|
||||
* `line`: The original line number associated with this source node, or null if
|
||||
it isn't associated with an original line.
|
||||
|
||||
* `column`: The original column number associated with this source node, or null
|
||||
if it isn't associated with an original column.
|
||||
|
||||
* `source`: The original source's filename.
|
||||
|
||||
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
|
||||
below.
|
||||
|
||||
* `name`: Optional. The original identifier.
|
||||
|
||||
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer)
|
||||
|
||||
Creates a SourceNode from generated code and a SourceMapConsumer.
|
||||
|
||||
* `code`: The generated code
|
||||
|
||||
* `sourceMapConsumer` The SourceMap for the generated code
|
||||
|
||||
#### SourceNode.prototype.add(chunk)
|
||||
|
||||
Add a chunk of generated JS to this source node.
|
||||
|
||||
* `chunk`: A string snippet of generated JS code, another instance of
|
||||
`SourceNode`, or an array where each member is one of those things.
|
||||
|
||||
#### SourceNode.prototype.prepend(chunk)
|
||||
|
||||
Prepend a chunk of generated JS to this source node.
|
||||
|
||||
* `chunk`: A string snippet of generated JS code, another instance of
|
||||
`SourceNode`, or an array where each member is one of those things.
|
||||
|
||||
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
|
||||
|
||||
Set the source content for a source file. This will be added to the
|
||||
`SourceMap` in the `sourcesContent` field.
|
||||
|
||||
* `sourceFile`: The filename of the source file
|
||||
|
||||
* `sourceContent`: The content of the source file
|
||||
|
||||
#### SourceNode.prototype.walk(fn)
|
||||
|
||||
Walk over the tree of JS snippets in this node and its children. The walking
|
||||
function is called once for each snippet of JS and is passed that snippet and
|
||||
the its original associated source's line/column location.
|
||||
|
||||
* `fn`: The traversal function.
|
||||
|
||||
#### SourceNode.prototype.walkSourceContents(fn)
|
||||
|
||||
Walk over the tree of SourceNodes. The walking function is called for each
|
||||
source file content and is passed the filename and source content.
|
||||
|
||||
* `fn`: The traversal function.
|
||||
|
||||
#### SourceNode.prototype.join(sep)
|
||||
|
||||
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
|
||||
between each of this source node's children.
|
||||
|
||||
* `sep`: The separator.
|
||||
|
||||
#### SourceNode.prototype.replaceRight(pattern, replacement)
|
||||
|
||||
Call `String.prototype.replace` on the very right-most source snippet. Useful
|
||||
for trimming whitespace from the end of a source node, etc.
|
||||
|
||||
* `pattern`: The pattern to replace.
|
||||
|
||||
* `replacement`: The thing to replace the pattern with.
|
||||
|
||||
#### SourceNode.prototype.toString()
|
||||
|
||||
Return the string representation of this source node. Walks over the tree and
|
||||
concatenates all the various snippets together to one string.
|
||||
|
||||
### SourceNode.prototype.toStringWithSourceMap(startOfSourceMap)
|
||||
|
||||
Returns the string representation of this tree of source nodes, plus a
|
||||
SourceMapGenerator which contains all the mappings between the generated and
|
||||
original sources.
|
||||
|
||||
The arguments are the same as those to `new SourceMapGenerator`.
|
||||
|
||||
## Tests
|
||||
|
||||
[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
|
||||
|
||||
Install NodeJS version 0.8.0 or greater, then run `node test/run-tests.js`.
|
||||
|
||||
To add new tests, create a new file named `test/test-<your new test name>.js`
|
||||
and export your test functions with names that start with "test", for example
|
||||
|
||||
exports["test doing the foo bar"] = function (assert, util) {
|
||||
...
|
||||
};
|
||||
|
||||
The new test will be located automatically when you run the suite.
|
||||
|
||||
The `util` argument is the test utility module located at `test/source-map/util`.
|
||||
|
||||
The `assert` argument is a cut down version of node's assert module. You have
|
||||
access to the following assertion functions:
|
||||
|
||||
* `doesNotThrow`
|
||||
|
||||
* `equal`
|
||||
|
||||
* `ok`
|
||||
|
||||
* `strictEqual`
|
||||
|
||||
* `throws`
|
||||
|
||||
(The reason for the restricted set of test functions is because we need the
|
||||
tests to run inside Firefox's test suite as well and so the assert module is
|
||||
shimmed in that environment. See `build/assert-shim.js`.)
|
||||
|
||||
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
|
||||
[feature]: https://wiki.mozilla.org/DevTools/Features/SourceMap
|
||||
[Dryice]: https://github.com/mozilla/dryice
|
|
@ -1,56 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
define('test/source-map/assert', ['exports'], function (exports) {
|
||||
|
||||
let do_throw = function (msg) {
|
||||
throw new Error(msg);
|
||||
};
|
||||
|
||||
exports.init = function (throw_fn) {
|
||||
do_throw = throw_fn;
|
||||
};
|
||||
|
||||
exports.doesNotThrow = function (fn) {
|
||||
try {
|
||||
fn();
|
||||
}
|
||||
catch (e) {
|
||||
do_throw(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
exports.equal = function (actual, expected, msg) {
|
||||
msg = msg || String(actual) + ' != ' + String(expected);
|
||||
if (actual != expected) {
|
||||
do_throw(msg);
|
||||
}
|
||||
};
|
||||
|
||||
exports.ok = function (val, msg) {
|
||||
msg = msg || String(val) + ' is falsey';
|
||||
if (!Boolean(val)) {
|
||||
do_throw(msg);
|
||||
}
|
||||
};
|
||||
|
||||
exports.strictEqual = function (actual, expected, msg) {
|
||||
msg = msg || String(actual) + ' !== ' + String(expected);
|
||||
if (actual !== expected) {
|
||||
do_throw(msg);
|
||||
}
|
||||
};
|
||||
|
||||
exports.throws = function (fn) {
|
||||
try {
|
||||
fn();
|
||||
do_throw('Expected an error to be thrown, but it wasn\'t.');
|
||||
}
|
||||
catch (e) {
|
||||
}
|
||||
};
|
||||
|
||||
});
|
|
@ -1,152 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
|
||||
/**
|
||||
* Define a module along with a payload.
|
||||
* @param {string} moduleName Name for the payload
|
||||
* @param {ignored} deps Ignored. For compatibility with CommonJS AMD Spec
|
||||
* @param {function} payload Function with (require, exports, module) params
|
||||
*/
|
||||
function define(moduleName, deps, payload) {
|
||||
if (typeof moduleName != "string") {
|
||||
throw new TypeError('Expected string, got: ' + moduleName);
|
||||
}
|
||||
|
||||
if (arguments.length == 2) {
|
||||
payload = deps;
|
||||
}
|
||||
|
||||
if (moduleName in define.modules) {
|
||||
throw new Error("Module already defined: " + moduleName);
|
||||
}
|
||||
define.modules[moduleName] = payload;
|
||||
};
|
||||
|
||||
/**
|
||||
* The global store of un-instantiated modules
|
||||
*/
|
||||
define.modules = {};
|
||||
|
||||
|
||||
/**
|
||||
* We invoke require() in the context of a Domain so we can have multiple
|
||||
* sets of modules running separate from each other.
|
||||
* This contrasts with JSMs which are singletons, Domains allows us to
|
||||
* optionally load a CommonJS module twice with separate data each time.
|
||||
* Perhaps you want 2 command lines with a different set of commands in each,
|
||||
* for example.
|
||||
*/
|
||||
function Domain() {
|
||||
this.modules = {};
|
||||
this._currentModule = null;
|
||||
}
|
||||
|
||||
(function () {
|
||||
|
||||
/**
|
||||
* Lookup module names and resolve them by calling the definition function if
|
||||
* needed.
|
||||
* There are 2 ways to call this, either with an array of dependencies and a
|
||||
* callback to call when the dependencies are found (which can happen
|
||||
* asynchronously in an in-page context) or with a single string an no callback
|
||||
* where the dependency is resolved synchronously and returned.
|
||||
* The API is designed to be compatible with the CommonJS AMD spec and
|
||||
* RequireJS.
|
||||
* @param {string[]|string} deps A name, or names for the payload
|
||||
* @param {function|undefined} callback Function to call when the dependencies
|
||||
* are resolved
|
||||
* @return {undefined|object} The module required or undefined for
|
||||
* array/callback method
|
||||
*/
|
||||
Domain.prototype.require = function(deps, callback) {
|
||||
if (Array.isArray(deps)) {
|
||||
var params = deps.map(function(dep) {
|
||||
return this.lookup(dep);
|
||||
}, this);
|
||||
if (callback) {
|
||||
callback.apply(null, params);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
else {
|
||||
return this.lookup(deps);
|
||||
}
|
||||
};
|
||||
|
||||
function normalize(path) {
|
||||
var bits = path.split('/');
|
||||
var i = 1;
|
||||
while (i < bits.length) {
|
||||
if (bits[i] === '..') {
|
||||
bits.splice(i-1, 1);
|
||||
} else if (bits[i] === '.') {
|
||||
bits.splice(i, 1);
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return bits.join('/');
|
||||
}
|
||||
|
||||
function join(a, b) {
|
||||
a = a.trim();
|
||||
b = b.trim();
|
||||
if (/^\//.test(b)) {
|
||||
return b;
|
||||
} else {
|
||||
return a.replace(/\/*$/, '/') + b;
|
||||
}
|
||||
}
|
||||
|
||||
function dirname(path) {
|
||||
var bits = path.split('/');
|
||||
bits.pop();
|
||||
return bits.join('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup module names and resolve them by calling the definition function if
|
||||
* needed.
|
||||
* @param {string} moduleName A name for the payload to lookup
|
||||
* @return {object} The module specified by aModuleName or null if not found.
|
||||
*/
|
||||
Domain.prototype.lookup = function(moduleName) {
|
||||
if (/^\./.test(moduleName)) {
|
||||
moduleName = normalize(join(dirname(this._currentModule), moduleName));
|
||||
}
|
||||
|
||||
if (moduleName in this.modules) {
|
||||
var module = this.modules[moduleName];
|
||||
return module;
|
||||
}
|
||||
|
||||
if (!(moduleName in define.modules)) {
|
||||
throw new Error("Module not defined: " + moduleName);
|
||||
}
|
||||
|
||||
var module = define.modules[moduleName];
|
||||
|
||||
if (typeof module == "function") {
|
||||
var exports = {};
|
||||
var previousModule = this._currentModule;
|
||||
this._currentModule = moduleName;
|
||||
module(this.require.bind(this), exports, { id: moduleName, uri: "" });
|
||||
this._currentModule = previousModule;
|
||||
module = exports;
|
||||
}
|
||||
|
||||
// cache the resulting module object for next time
|
||||
this.modules[moduleName] = module;
|
||||
|
||||
return module;
|
||||
};
|
||||
|
||||
}());
|
||||
|
||||
define.Domain = Domain;
|
||||
define.globalDomain = new Domain();
|
||||
var require = define.globalDomain.require.bind(define.globalDomain);
|
|
@ -1,20 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
|
||||
/*
|
||||
* WARNING!
|
||||
*
|
||||
* Do not edit this file directly, it is built from the sources at
|
||||
* https://github.com/mozilla/source-map/
|
||||
*/
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
this.EXPORTED_SYMBOLS = [ "SourceMapConsumer", "SourceMapGenerator", "SourceNode" ];
|
||||
|
||||
Components.utils.import('resource://gre/modules/devtools/Require.jsm');
|
|
@ -1,18 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
|
||||
/*
|
||||
* WARNING!
|
||||
*
|
||||
* Do not edit this file directly, it is built from the sources at
|
||||
* https://github.com/mozilla/source-map/
|
||||
*/
|
||||
|
||||
Components.utils.import('resource://gre/modules/devtools/Require.jsm');
|
||||
Components.utils.import('resource://gre/modules/devtools/SourceMap.jsm');
|
||||
|
||||
this.EXPORTED_SYMBOLS = [ "define", "runSourceMapTests" ];
|
|
@ -1,8 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
window.sourceMap = {
|
||||
SourceMapConsumer: require('source-map/source-map-consumer').SourceMapConsumer,
|
||||
SourceMapGenerator: require('source-map/source-map-generator').SourceMapGenerator,
|
||||
SourceNode: require('source-map/source-node').SourceNode
|
||||
};
|
|
@ -1,6 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
this.SourceMapConsumer = require('source-map/source-map-consumer').SourceMapConsumer;
|
||||
this.SourceMapGenerator = require('source-map/source-map-generator').SourceMapGenerator;
|
||||
this.SourceNode = require('source-map/source-node').SourceNode;
|
|
@ -1,21 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
function runSourceMapTests(modName, do_throw) {
|
||||
let mod = require(modName);
|
||||
let assert = require('test/source-map/assert');
|
||||
let util = require('test/source-map/util');
|
||||
|
||||
assert.init(do_throw);
|
||||
|
||||
for (let k in mod) {
|
||||
if (/^test/.test(k)) {
|
||||
mod[k](assert, util);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
this.runSourceMapTests = runSourceMapTests;
|
|
@ -1,8 +0,0 @@
|
|||
/*
|
||||
* WARNING!
|
||||
*
|
||||
* Do not edit this file directly, it is built from the sources at
|
||||
* https://github.com/mozilla/source-map/
|
||||
*/
|
||||
|
||||
Components.utils.import('resource://test/Utils.jsm');
|
|
@ -1,3 +0,0 @@
|
|||
function run_test() {
|
||||
runSourceMapTests('{THIS_MODULE}', do_throw);
|
||||
}
|
|
@ -1,8 +0,0 @@
|
|||
/*
|
||||
* Copyright 2009-2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE.txt or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator;
|
||||
exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer;
|
||||
exports.SourceNode = require('./source-map/source-node').SourceNode;
|
|
@ -1,96 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
if (typeof define !== 'function') {
|
||||
var define = require('amdefine')(module);
|
||||
}
|
||||
define(function (require, exports, module) {
|
||||
|
||||
var util = require('./util');
|
||||
|
||||
/**
|
||||
* A data structure which is a combination of an array and a set. Adding a new
|
||||
* member is O(1), testing for membership is O(1), and finding the index of an
|
||||
* element is O(1). Removing elements from the set is not supported. Only
|
||||
* strings are supported for membership.
|
||||
*/
|
||||
function ArraySet() {
|
||||
this._array = [];
|
||||
this._set = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Static method for creating ArraySet instances from an existing array.
|
||||
*/
|
||||
ArraySet.fromArray = function ArraySet_fromArray(aArray) {
|
||||
var set = new ArraySet();
|
||||
for (var i = 0, len = aArray.length; i < len; i++) {
|
||||
set.add(aArray[i]);
|
||||
}
|
||||
return set;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add the given string to this set.
|
||||
*
|
||||
* @param String aStr
|
||||
*/
|
||||
ArraySet.prototype.add = function ArraySet_add(aStr) {
|
||||
if (this.has(aStr)) {
|
||||
// Already a member; nothing to do.
|
||||
return;
|
||||
}
|
||||
var idx = this._array.length;
|
||||
this._array.push(aStr);
|
||||
this._set[util.toSetString(aStr)] = idx;
|
||||
};
|
||||
|
||||
/**
|
||||
* Is the given string a member of this set?
|
||||
*
|
||||
* @param String aStr
|
||||
*/
|
||||
ArraySet.prototype.has = function ArraySet_has(aStr) {
|
||||
return Object.prototype.hasOwnProperty.call(this._set,
|
||||
util.toSetString(aStr));
|
||||
};
|
||||
|
||||
/**
|
||||
* What is the index of the given string in the array?
|
||||
*
|
||||
* @param String aStr
|
||||
*/
|
||||
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
|
||||
if (this.has(aStr)) {
|
||||
return this._set[util.toSetString(aStr)];
|
||||
}
|
||||
throw new Error('"' + aStr + '" is not in the set.');
|
||||
};
|
||||
|
||||
/**
|
||||
* What is the element at the given index?
|
||||
*
|
||||
* @param Number aIdx
|
||||
*/
|
||||
ArraySet.prototype.at = function ArraySet_at(aIdx) {
|
||||
if (aIdx >= 0 && aIdx < this._array.length) {
|
||||
return this._array[aIdx];
|
||||
}
|
||||
throw new Error('No element indexed by ' + aIdx);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the array representation of this set (which has the proper indices
|
||||
* indicated by indexOf). Note that this is a copy of the internal array used
|
||||
* for storing the members so that no one can mess with internal state.
|
||||
*/
|
||||
ArraySet.prototype.toArray = function ArraySet_toArray() {
|
||||
return this._array.slice();
|
||||
};
|
||||
|
||||
exports.ArraySet = ArraySet;
|
||||
|
||||
});
|
|
@ -1,144 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Based on the Base 64 VLQ implementation in Closure Compiler:
|
||||
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
|
||||
*
|
||||
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Google Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
if (typeof define !== 'function') {
|
||||
var define = require('amdefine')(module);
|
||||
}
|
||||
define(function (require, exports, module) {
|
||||
|
||||
var base64 = require('./base64');
|
||||
|
||||
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
|
||||
// length quantities we use in the source map spec, the first bit is the sign,
|
||||
// the next four bits are the actual value, and the 6th bit is the
|
||||
// continuation bit. The continuation bit tells us whether there are more
|
||||
// digits in this value following this digit.
|
||||
//
|
||||
// Continuation
|
||||
// | Sign
|
||||
// | |
|
||||
// V V
|
||||
// 101011
|
||||
|
||||
var VLQ_BASE_SHIFT = 5;
|
||||
|
||||
// binary: 100000
|
||||
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
|
||||
|
||||
// binary: 011111
|
||||
var VLQ_BASE_MASK = VLQ_BASE - 1;
|
||||
|
||||
// binary: 100000
|
||||
var VLQ_CONTINUATION_BIT = VLQ_BASE;
|
||||
|
||||
/**
|
||||
* Converts from a two-complement value to a value where the sign bit is
|
||||
* is placed in the least significant bit. For example, as decimals:
|
||||
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
|
||||
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
|
||||
*/
|
||||
function toVLQSigned(aValue) {
|
||||
return aValue < 0
|
||||
? ((-aValue) << 1) + 1
|
||||
: (aValue << 1) + 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts to a two-complement value from a value where the sign bit is
|
||||
* is placed in the least significant bit. For example, as decimals:
|
||||
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
|
||||
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
|
||||
*/
|
||||
function fromVLQSigned(aValue) {
|
||||
var isNegative = (aValue & 1) === 1;
|
||||
var shifted = aValue >> 1;
|
||||
return isNegative
|
||||
? -shifted
|
||||
: shifted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the base 64 VLQ encoded value.
|
||||
*/
|
||||
exports.encode = function base64VLQ_encode(aValue) {
|
||||
var encoded = "";
|
||||
var digit;
|
||||
|
||||
var vlq = toVLQSigned(aValue);
|
||||
|
||||
do {
|
||||
digit = vlq & VLQ_BASE_MASK;
|
||||
vlq >>>= VLQ_BASE_SHIFT;
|
||||
if (vlq > 0) {
|
||||
// There are still more digits in this value, so we must make sure the
|
||||
// continuation bit is marked.
|
||||
digit |= VLQ_CONTINUATION_BIT;
|
||||
}
|
||||
encoded += base64.encode(digit);
|
||||
} while (vlq > 0);
|
||||
|
||||
return encoded;
|
||||
};
|
||||
|
||||
/**
|
||||
* Decodes the next base 64 VLQ value from the given string and returns the
|
||||
* value and the rest of the string.
|
||||
*/
|
||||
exports.decode = function base64VLQ_decode(aStr) {
|
||||
var i = 0;
|
||||
var strLen = aStr.length;
|
||||
var result = 0;
|
||||
var shift = 0;
|
||||
var continuation, digit;
|
||||
|
||||
do {
|
||||
if (i >= strLen) {
|
||||
throw new Error("Expected more digits in base 64 VLQ value.");
|
||||
}
|
||||
digit = base64.decode(aStr.charAt(i++));
|
||||
continuation = !!(digit & VLQ_CONTINUATION_BIT);
|
||||
digit &= VLQ_BASE_MASK;
|
||||
result = result + (digit << shift);
|
||||
shift += VLQ_BASE_SHIFT;
|
||||
} while (continuation);
|
||||
|
||||
return {
|
||||
value: fromVLQSigned(result),
|
||||
rest: aStr.slice(i)
|
||||
};
|
||||
};
|
||||
|
||||
});
|
|
@ -1,42 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
if (typeof define !== 'function') {
|
||||
var define = require('amdefine')(module);
|
||||
}
|
||||
define(function (require, exports, module) {
|
||||
|
||||
var charToIntMap = {};
|
||||
var intToCharMap = {};
|
||||
|
||||
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
|
||||
.split('')
|
||||
.forEach(function (ch, index) {
|
||||
charToIntMap[ch] = index;
|
||||
intToCharMap[index] = ch;
|
||||
});
|
||||
|
||||
/**
|
||||
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
|
||||
*/
|
||||
exports.encode = function base64_encode(aNumber) {
|
||||
if (aNumber in intToCharMap) {
|
||||
return intToCharMap[aNumber];
|
||||
}
|
||||
throw new TypeError("Must be between 0 and 63: " + aNumber);
|
||||
};
|
||||
|
||||
/**
|
||||
* Decode a single base 64 digit to an integer.
|
||||
*/
|
||||
exports.decode = function base64_decode(aChar) {
|
||||
if (aChar in charToIntMap) {
|
||||
return charToIntMap[aChar];
|
||||
}
|
||||
throw new TypeError("Not a valid base 64 digit: " + aChar);
|
||||
};
|
||||
|
||||
});
|
|
@ -1,81 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
if (typeof define !== 'function') {
|
||||
var define = require('amdefine')(module);
|
||||
}
|
||||
define(function (require, exports, module) {
|
||||
|
||||
/**
|
||||
* Recursive implementation of binary search.
|
||||
*
|
||||
* @param aLow Indices here and lower do not contain the needle.
|
||||
* @param aHigh Indices here and higher do not contain the needle.
|
||||
* @param aNeedle The element being searched for.
|
||||
* @param aHaystack The non-empty array being searched.
|
||||
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
|
||||
*/
|
||||
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
|
||||
// This function terminates when one of the following is true:
|
||||
//
|
||||
// 1. We find the exact element we are looking for.
|
||||
//
|
||||
// 2. We did not find the exact element, but we can return the next
|
||||
// closest element that is less than that element.
|
||||
//
|
||||
// 3. We did not find the exact element, and there is no next-closest
|
||||
// element which is less than the one we are searching for, so we
|
||||
// return null.
|
||||
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
|
||||
var cmp = aCompare(aNeedle, aHaystack[mid]);
|
||||
if (cmp === 0) {
|
||||
// Found the element we are looking for.
|
||||
return aHaystack[mid];
|
||||
}
|
||||
else if (cmp > 0) {
|
||||
// aHaystack[mid] is greater than our needle.
|
||||
if (aHigh - mid > 1) {
|
||||
// The element is in the upper half.
|
||||
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
|
||||
}
|
||||
// We did not find an exact match, return the next closest one
|
||||
// (termination case 2).
|
||||
return aHaystack[mid];
|
||||
}
|
||||
else {
|
||||
// aHaystack[mid] is less than our needle.
|
||||
if (mid - aLow > 1) {
|
||||
// The element is in the lower half.
|
||||
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
|
||||
}
|
||||
// The exact needle element was not found in this haystack. Determine if
|
||||
// we are in termination case (2) or (3) and return the appropriate thing.
|
||||
return aLow < 0
|
||||
? null
|
||||
: aHaystack[aLow];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is an implementation of binary search which will always try and return
|
||||
* the next lowest value checked if there is no exact hit. This is because
|
||||
* mappings between original and generated line/col pairs are single points,
|
||||
* and there is an implicit region between each of them, so a miss just means
|
||||
* that you aren't on the very start of a region.
|
||||
*
|
||||
* @param aNeedle The element you are looking for.
|
||||
* @param aHaystack The array that is being searched.
|
||||
* @param aCompare A function which takes the needle and an element in the
|
||||
* array and returns -1, 0, or 1 depending on whether the needle is less
|
||||
* than, equal to, or greater than the element, respectively.
|
||||
*/
|
||||
exports.search = function search(aNeedle, aHaystack, aCompare) {
|
||||
return aHaystack.length > 0
|
||||
? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
|
||||
: null;
|
||||
};
|
||||
|
||||
});
|
|
@ -1,426 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
if (typeof define !== 'function') {
|
||||
var define = require('amdefine')(module);
|
||||
}
|
||||
define(function (require, exports, module) {
|
||||
|
||||
var util = require('./util');
|
||||
var binarySearch = require('./binary-search');
|
||||
var ArraySet = require('./array-set').ArraySet;
|
||||
var base64VLQ = require('./base64-vlq');
|
||||
|
||||
/**
|
||||
* A SourceMapConsumer instance represents a parsed source map which we can
|
||||
* query for information about the original file positions by giving it a file
|
||||
* position in the generated source.
|
||||
*
|
||||
* The only parameter is the raw source map (either as a JSON string, or
|
||||
* already parsed to an object). According to the spec, source maps have the
|
||||
* following attributes:
|
||||
*
|
||||
* - version: Which version of the source map spec this map is following.
|
||||
* - sources: An array of URLs to the original source files.
|
||||
* - names: An array of identifiers which can be referrenced by individual mappings.
|
||||
* - sourceRoot: Optional. The URL root from which all sources are relative.
|
||||
* - sourcesContent: Optional. An array of contents of the original source files.
|
||||
* - mappings: A string of base64 VLQs which contain the actual mappings.
|
||||
* - file: The generated file this source map is associated with.
|
||||
*
|
||||
* Here is an example source map, taken from the source map spec[0]:
|
||||
*
|
||||
* {
|
||||
* version : 3,
|
||||
* file: "out.js",
|
||||
* sourceRoot : "",
|
||||
* sources: ["foo.js", "bar.js"],
|
||||
* names: ["src", "maps", "are", "fun"],
|
||||
* mappings: "AA,AB;;ABCDE;"
|
||||
* }
|
||||
*
|
||||
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
|
||||
*/
|
||||
function SourceMapConsumer(aSourceMap) {
|
||||
var sourceMap = aSourceMap;
|
||||
if (typeof aSourceMap === 'string') {
|
||||
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
|
||||
}
|
||||
|
||||
var version = util.getArg(sourceMap, 'version');
|
||||
var sources = util.getArg(sourceMap, 'sources');
|
||||
var names = util.getArg(sourceMap, 'names');
|
||||
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
|
||||
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
|
||||
var mappings = util.getArg(sourceMap, 'mappings');
|
||||
var file = util.getArg(sourceMap, 'file');
|
||||
|
||||
if (version !== this._version) {
|
||||
throw new Error('Unsupported version: ' + version);
|
||||
}
|
||||
|
||||
this._names = ArraySet.fromArray(names);
|
||||
this._sources = ArraySet.fromArray(sources);
|
||||
this.sourceRoot = sourceRoot;
|
||||
this.sourcesContent = sourcesContent;
|
||||
this.file = file;
|
||||
|
||||
// `this._generatedMappings` and `this._originalMappings` hold the parsed
|
||||
// mapping coordinates from the source map's "mappings" attribute. Each
|
||||
// object in the array is of the form
|
||||
//
|
||||
// {
|
||||
// generatedLine: The line number in the generated code,
|
||||
// generatedColumn: The column number in the generated code,
|
||||
// source: The path to the original source file that generated this
|
||||
// chunk of code,
|
||||
// originalLine: The line number in the original source that
|
||||
// corresponds to this chunk of generated code,
|
||||
// originalColumn: The column number in the original source that
|
||||
// corresponds to this chunk of generated code,
|
||||
// name: The name of the original symbol which generated this chunk of
|
||||
// code.
|
||||
// }
|
||||
//
|
||||
// All properties except for `generatedLine` and `generatedColumn` can be
|
||||
// `null`.
|
||||
//
|
||||
// `this._generatedMappings` is ordered by the generated positions.
|
||||
//
|
||||
// `this._originalMappings` is ordered by the original positions.
|
||||
this._generatedMappings = [];
|
||||
this._originalMappings = [];
|
||||
this._parseMappings(mappings, sourceRoot);
|
||||
}
|
||||
|
||||
/**
|
||||
* The version of the source mapping spec that we are consuming.
|
||||
*/
|
||||
SourceMapConsumer.prototype._version = 3;
|
||||
|
||||
/**
|
||||
* The list of original sources.
|
||||
*/
|
||||
Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
|
||||
get: function () {
|
||||
return this._sources.toArray().map(function (s) {
|
||||
return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
|
||||
}, this);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Parse the mappings in a string in to a data structure which we can easily
|
||||
* query (an ordered list in this._generatedMappings).
|
||||
*/
|
||||
SourceMapConsumer.prototype._parseMappings =
|
||||
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
|
||||
var generatedLine = 1;
|
||||
var previousGeneratedColumn = 0;
|
||||
var previousOriginalLine = 0;
|
||||
var previousOriginalColumn = 0;
|
||||
var previousSource = 0;
|
||||
var previousName = 0;
|
||||
var mappingSeparator = /^[,;]/;
|
||||
var str = aStr;
|
||||
var mapping;
|
||||
var temp;
|
||||
|
||||
while (str.length > 0) {
|
||||
if (str.charAt(0) === ';') {
|
||||
generatedLine++;
|
||||
str = str.slice(1);
|
||||
previousGeneratedColumn = 0;
|
||||
}
|
||||
else if (str.charAt(0) === ',') {
|
||||
str = str.slice(1);
|
||||
}
|
||||
else {
|
||||
mapping = {};
|
||||
mapping.generatedLine = generatedLine;
|
||||
|
||||
// Generated column.
|
||||
temp = base64VLQ.decode(str);
|
||||
mapping.generatedColumn = previousGeneratedColumn + temp.value;
|
||||
previousGeneratedColumn = mapping.generatedColumn;
|
||||
str = temp.rest;
|
||||
|
||||
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
|
||||
// Original source.
|
||||
temp = base64VLQ.decode(str);
|
||||
mapping.source = this._sources.at(previousSource + temp.value);
|
||||
previousSource += temp.value;
|
||||
str = temp.rest;
|
||||
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
|
||||
throw new Error('Found a source, but no line and column');
|
||||
}
|
||||
|
||||
// Original line.
|
||||
temp = base64VLQ.decode(str);
|
||||
mapping.originalLine = previousOriginalLine + temp.value;
|
||||
previousOriginalLine = mapping.originalLine;
|
||||
// Lines are stored 0-based
|
||||
mapping.originalLine += 1;
|
||||
str = temp.rest;
|
||||
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
|
||||
throw new Error('Found a source and line, but no column');
|
||||
}
|
||||
|
||||
// Original column.
|
||||
temp = base64VLQ.decode(str);
|
||||
mapping.originalColumn = previousOriginalColumn + temp.value;
|
||||
previousOriginalColumn = mapping.originalColumn;
|
||||
str = temp.rest;
|
||||
|
||||
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
|
||||
// Original name.
|
||||
temp = base64VLQ.decode(str);
|
||||
mapping.name = this._names.at(previousName + temp.value);
|
||||
previousName += temp.value;
|
||||
str = temp.rest;
|
||||
}
|
||||
}
|
||||
|
||||
this._generatedMappings.push(mapping);
|
||||
if (typeof mapping.originalLine === 'number') {
|
||||
this._originalMappings.push(mapping);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this._originalMappings.sort(this._compareOriginalPositions);
|
||||
};
|
||||
|
||||
/**
|
||||
* Comparator between two mappings where the original positions are compared.
|
||||
*/
|
||||
SourceMapConsumer.prototype._compareOriginalPositions =
|
||||
function SourceMapConsumer_compareOriginalPositions(mappingA, mappingB) {
|
||||
if (mappingA.source > mappingB.source) {
|
||||
return 1;
|
||||
}
|
||||
else if (mappingA.source < mappingB.source) {
|
||||
return -1;
|
||||
}
|
||||
else {
|
||||
var cmp = mappingA.originalLine - mappingB.originalLine;
|
||||
return cmp === 0
|
||||
? mappingA.originalColumn - mappingB.originalColumn
|
||||
: cmp;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Comparator between two mappings where the generated positions are compared.
|
||||
*/
|
||||
SourceMapConsumer.prototype._compareGeneratedPositions =
|
||||
function SourceMapConsumer_compareGeneratedPositions(mappingA, mappingB) {
|
||||
var cmp = mappingA.generatedLine - mappingB.generatedLine;
|
||||
return cmp === 0
|
||||
? mappingA.generatedColumn - mappingB.generatedColumn
|
||||
: cmp;
|
||||
};
|
||||
|
||||
/**
|
||||
* Find the mapping that best matches the hypothetical "needle" mapping that
|
||||
* we are searching for in the given "haystack" of mappings.
|
||||
*/
|
||||
SourceMapConsumer.prototype._findMapping =
|
||||
function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
|
||||
aColumnName, aComparator) {
|
||||
// To return the position we are searching for, we must first find the
|
||||
// mapping for the given position and then return the opposite position it
|
||||
// points to. Because the mappings are sorted, we can use binary search to
|
||||
// find the best mapping.
|
||||
|
||||
if (aNeedle[aLineName] <= 0) {
|
||||
throw new TypeError('Line must be greater than or equal to 1, got '
|
||||
+ aNeedle[aLineName]);
|
||||
}
|
||||
if (aNeedle[aColumnName] < 0) {
|
||||
throw new TypeError('Column must be greater than or equal to 0, got '
|
||||
+ aNeedle[aColumnName]);
|
||||
}
|
||||
|
||||
return binarySearch.search(aNeedle, aMappings, aComparator);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the original source, line, and column information for the generated
|
||||
* source's line and column positions provided. The only argument is an object
|
||||
* with the following properties:
|
||||
*
|
||||
* - line: The line number in the generated source.
|
||||
* - column: The column number in the generated source.
|
||||
*
|
||||
* and an object is returned with the following properties:
|
||||
*
|
||||
* - source: The original source file, or null.
|
||||
* - line: The line number in the original source, or null.
|
||||
* - column: The column number in the original source, or null.
|
||||
* - name: The original identifier, or null.
|
||||
*/
|
||||
SourceMapConsumer.prototype.originalPositionFor =
|
||||
function SourceMapConsumer_originalPositionFor(aArgs) {
|
||||
var needle = {
|
||||
generatedLine: util.getArg(aArgs, 'line'),
|
||||
generatedColumn: util.getArg(aArgs, 'column')
|
||||
};
|
||||
|
||||
var mapping = this._findMapping(needle,
|
||||
this._generatedMappings,
|
||||
"generatedLine",
|
||||
"generatedColumn",
|
||||
this._compareGeneratedPositions);
|
||||
|
||||
if (mapping) {
|
||||
var source = util.getArg(mapping, 'source', null);
|
||||
if (source && this.sourceRoot) {
|
||||
source = util.join(this.sourceRoot, source);
|
||||
}
|
||||
return {
|
||||
source: source,
|
||||
line: util.getArg(mapping, 'originalLine', null),
|
||||
column: util.getArg(mapping, 'originalColumn', null),
|
||||
name: util.getArg(mapping, 'name', null)
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
source: null,
|
||||
line: null,
|
||||
column: null,
|
||||
name: null
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the original source content. The only argument is
|
||||
* the url of the original source file. Returns null if no
|
||||
* original source content is availible.
|
||||
*/
|
||||
SourceMapConsumer.prototype.sourceContentFor =
|
||||
function SourceMapConsumer_sourceContentFor(aSource) {
|
||||
if (!this.sourcesContent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (this.sourceRoot) {
|
||||
// Try to remove the sourceRoot
|
||||
var relativeUrl = util.relative(this.sourceRoot, aSource);
|
||||
if (this._sources.has(relativeUrl)) {
|
||||
return this.sourcesContent[this._sources.indexOf(relativeUrl)];
|
||||
}
|
||||
}
|
||||
|
||||
if (this._sources.has(aSource)) {
|
||||
return this.sourcesContent[this._sources.indexOf(aSource)];
|
||||
}
|
||||
|
||||
throw new Error('"' + aSource + '" is not in the SourceMap.');
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the generated line and column information for the original source,
|
||||
* line, and column positions provided. The only argument is an object with
|
||||
* the following properties:
|
||||
*
|
||||
* - source: The filename of the original source.
|
||||
* - line: The line number in the original source.
|
||||
* - column: The column number in the original source.
|
||||
*
|
||||
* and an object is returned with the following properties:
|
||||
*
|
||||
* - line: The line number in the generated source, or null.
|
||||
* - column: The column number in the generated source, or null.
|
||||
*/
|
||||
SourceMapConsumer.prototype.generatedPositionFor =
|
||||
function SourceMapConsumer_generatedPositionFor(aArgs) {
|
||||
var needle = {
|
||||
source: util.getArg(aArgs, 'source'),
|
||||
originalLine: util.getArg(aArgs, 'line'),
|
||||
originalColumn: util.getArg(aArgs, 'column')
|
||||
};
|
||||
|
||||
if (this.sourceRoot) {
|
||||
needle.source = util.relative(this.sourceRoot, needle.source);
|
||||
}
|
||||
|
||||
var mapping = this._findMapping(needle,
|
||||
this._originalMappings,
|
||||
"originalLine",
|
||||
"originalColumn",
|
||||
this._compareOriginalPositions);
|
||||
|
||||
if (mapping) {
|
||||
return {
|
||||
line: util.getArg(mapping, 'generatedLine', null),
|
||||
column: util.getArg(mapping, 'generatedColumn', null)
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
line: null,
|
||||
column: null
|
||||
};
|
||||
};
|
||||
|
||||
SourceMapConsumer.GENERATED_ORDER = 1;
|
||||
SourceMapConsumer.ORIGINAL_ORDER = 2;
|
||||
|
||||
/**
|
||||
* Iterate over each mapping between an original source/line/column and a
|
||||
* generated line/column in this source map.
|
||||
*
|
||||
* @param Function aCallback
|
||||
* The function that is called with each mapping.
|
||||
* @param Object aContext
|
||||
* Optional. If specified, this object will be the value of `this` every
|
||||
* time that `aCallback` is called.
|
||||
* @param aOrder
|
||||
* Either `SourceMapConsumer.GENERATED_ORDER` or
|
||||
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
|
||||
* iterate over the mappings sorted by the generated file's line/column
|
||||
* order or the original's source/line/column order, respectively. Defaults to
|
||||
* `SourceMapConsumer.GENERATED_ORDER`.
|
||||
*/
|
||||
SourceMapConsumer.prototype.eachMapping =
|
||||
function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
|
||||
var context = aContext || null;
|
||||
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
|
||||
|
||||
var mappings;
|
||||
switch (order) {
|
||||
case SourceMapConsumer.GENERATED_ORDER:
|
||||
mappings = this._generatedMappings;
|
||||
break;
|
||||
case SourceMapConsumer.ORIGINAL_ORDER:
|
||||
mappings = this._originalMappings;
|
||||
break;
|
||||
default:
|
||||
throw new Error("Unknown order of iteration.");
|
||||
}
|
||||
|
||||
var sourceRoot = this.sourceRoot;
|
||||
mappings.map(function (mapping) {
|
||||
var source = mapping.source;
|
||||
if (source && sourceRoot) {
|
||||
source = util.join(sourceRoot, source);
|
||||
}
|
||||
return {
|
||||
source: source,
|
||||
generatedLine: mapping.generatedLine,
|
||||
generatedColumn: mapping.generatedColumn,
|
||||
originalLine: mapping.originalLine,
|
||||
originalColumn: mapping.originalColumn,
|
||||
name: mapping.name
|
||||
};
|
||||
}).forEach(aCallback, context);
|
||||
};
|
||||
|
||||
exports.SourceMapConsumer = SourceMapConsumer;
|
||||
|
||||
});
|
|
@ -1,381 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
if (typeof define !== 'function') {
|
||||
var define = require('amdefine')(module);
|
||||
}
|
||||
define(function (require, exports, module) {
|
||||
|
||||
var base64VLQ = require('./base64-vlq');
|
||||
var util = require('./util');
|
||||
var ArraySet = require('./array-set').ArraySet;
|
||||
|
||||
/**
|
||||
* An instance of the SourceMapGenerator represents a source map which is
|
||||
* being built incrementally. To create a new one, you must pass an object
|
||||
* with the following properties:
|
||||
*
|
||||
* - file: The filename of the generated source.
|
||||
* - sourceRoot: An optional root for all URLs in this source map.
|
||||
*/
|
||||
function SourceMapGenerator(aArgs) {
|
||||
this._file = util.getArg(aArgs, 'file');
|
||||
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
|
||||
this._sources = new ArraySet();
|
||||
this._names = new ArraySet();
|
||||
this._mappings = [];
|
||||
this._sourcesContents = null;
|
||||
}
|
||||
|
||||
SourceMapGenerator.prototype._version = 3;
|
||||
|
||||
/**
|
||||
* Creates a new SourceMapGenerator based on a SourceMapConsumer
|
||||
*
|
||||
* @param aSourceMapConsumer The SourceMap.
|
||||
*/
|
||||
SourceMapGenerator.fromSourceMap =
|
||||
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
|
||||
var sourceRoot = aSourceMapConsumer.sourceRoot;
|
||||
var generator = new SourceMapGenerator({
|
||||
file: aSourceMapConsumer.file,
|
||||
sourceRoot: sourceRoot
|
||||
});
|
||||
aSourceMapConsumer.eachMapping(function (mapping) {
|
||||
var newMapping = {
|
||||
generated: {
|
||||
line: mapping.generatedLine,
|
||||
column: mapping.generatedColumn
|
||||
}
|
||||
};
|
||||
|
||||
if (mapping.source) {
|
||||
newMapping.source = mapping.source;
|
||||
if (sourceRoot) {
|
||||
newMapping.source = util.relative(sourceRoot, newMapping.source);
|
||||
}
|
||||
|
||||
newMapping.original = {
|
||||
line: mapping.originalLine,
|
||||
column: mapping.originalColumn
|
||||
};
|
||||
|
||||
if (mapping.name) {
|
||||
newMapping.name = mapping.name;
|
||||
}
|
||||
}
|
||||
|
||||
generator.addMapping(newMapping);
|
||||
});
|
||||
aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
||||
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
||||
if (content) {
|
||||
generator.setSourceContent(sourceFile, content);
|
||||
}
|
||||
});
|
||||
return generator;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a single mapping from original source line and column to the generated
|
||||
* source's line and column for this source map being created. The mapping
|
||||
* object should have the following properties:
|
||||
*
|
||||
* - generated: An object with the generated line and column positions.
|
||||
* - original: An object with the original line and column positions.
|
||||
* - source: The original source file (relative to the sourceRoot).
|
||||
* - name: An optional original token name for this mapping.
|
||||
*/
|
||||
SourceMapGenerator.prototype.addMapping =
|
||||
function SourceMapGenerator_addMapping(aArgs) {
|
||||
var generated = util.getArg(aArgs, 'generated');
|
||||
var original = util.getArg(aArgs, 'original', null);
|
||||
var source = util.getArg(aArgs, 'source', null);
|
||||
var name = util.getArg(aArgs, 'name', null);
|
||||
|
||||
this._validateMapping(generated, original, source, name);
|
||||
|
||||
if (source && !this._sources.has(source)) {
|
||||
this._sources.add(source);
|
||||
}
|
||||
|
||||
if (name && !this._names.has(name)) {
|
||||
this._names.add(name);
|
||||
}
|
||||
|
||||
this._mappings.push({
|
||||
generated: generated,
|
||||
original: original,
|
||||
source: source,
|
||||
name: name
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the source content for a source file.
|
||||
*/
|
||||
SourceMapGenerator.prototype.setSourceContent =
|
||||
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
|
||||
var source = aSourceFile;
|
||||
if (this._sourceRoot) {
|
||||
source = util.relative(this._sourceRoot, source);
|
||||
}
|
||||
|
||||
if (aSourceContent !== null) {
|
||||
// Add the source content to the _sourcesContents map.
|
||||
// Create a new _sourcesContents map if the property is null.
|
||||
if (!this._sourcesContents) {
|
||||
this._sourcesContents = {};
|
||||
}
|
||||
this._sourcesContents[util.toSetString(source)] = aSourceContent;
|
||||
} else {
|
||||
// Remove the source file from the _sourcesContents map.
|
||||
// If the _sourcesContents map is empty, set the property to null.
|
||||
delete this._sourcesContents[util.toSetString(source)];
|
||||
if (Object.keys(this._sourcesContents).length === 0) {
|
||||
this._sourcesContents = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies the mappings of a sub-source-map for a specific source file to the
|
||||
* source map being generated. Each mapping to the supplied source file is
|
||||
* rewritten using the supplied source map. Note: The resolution for the
|
||||
* resulting mappings is the minimium of this map and the supplied map.
|
||||
*
|
||||
* @param aSourceMapConsumer The source map to be applied.
|
||||
* @param aSourceFile Optional. The filename of the source file.
|
||||
* If omitted, SourceMapConsumer's file property will be used.
|
||||
*/
|
||||
SourceMapGenerator.prototype.applySourceMap =
|
||||
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) {
|
||||
// If aSourceFile is omitted, we will use the file property of the SourceMap
|
||||
if (!aSourceFile) {
|
||||
aSourceFile = aSourceMapConsumer.file;
|
||||
}
|
||||
var sourceRoot = this._sourceRoot;
|
||||
// Make "aSourceFile" relative if an absolute Url is passed.
|
||||
if (sourceRoot) {
|
||||
aSourceFile = util.relative(sourceRoot, aSourceFile);
|
||||
}
|
||||
// Applying the SourceMap can add and remove items from the sources and
|
||||
// the names array.
|
||||
var newSources = new ArraySet();
|
||||
var newNames = new ArraySet();
|
||||
|
||||
// Find mappings for the "aSourceFile"
|
||||
this._mappings.forEach(function (mapping) {
|
||||
if (mapping.source === aSourceFile && mapping.original) {
|
||||
// Check if it can be mapped by the source map, then update the mapping.
|
||||
var original = aSourceMapConsumer.originalPositionFor({
|
||||
line: mapping.original.line,
|
||||
column: mapping.original.column
|
||||
});
|
||||
if (original.source !== null) {
|
||||
// Copy mapping
|
||||
if (sourceRoot) {
|
||||
mapping.source = util.relative(sourceRoot, original.source);
|
||||
} else {
|
||||
mapping.source = original.source;
|
||||
}
|
||||
mapping.original.line = original.line;
|
||||
mapping.original.column = original.column;
|
||||
if (original.name !== null && mapping.name !== null) {
|
||||
// Only use the identifier name if it's an identifier
|
||||
// in both SourceMaps
|
||||
mapping.name = original.name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var source = mapping.source;
|
||||
if (source && !newSources.has(source)) {
|
||||
newSources.add(source);
|
||||
}
|
||||
|
||||
var name = mapping.name;
|
||||
if (name && !newNames.has(name)) {
|
||||
newNames.add(name);
|
||||
}
|
||||
|
||||
}, this);
|
||||
this._sources = newSources;
|
||||
this._names = newNames;
|
||||
|
||||
// Copy sourcesContents of applied map.
|
||||
aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
||||
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
||||
if (content) {
|
||||
if (sourceRoot) {
|
||||
sourceFile = util.relative(sourceRoot, sourceFile);
|
||||
}
|
||||
this.setSourceContent(sourceFile, content);
|
||||
}
|
||||
}, this);
|
||||
};
|
||||
|
||||
/**
|
||||
* A mapping can have one of the three levels of data:
|
||||
*
|
||||
* 1. Just the generated position.
|
||||
* 2. The Generated position, original position, and original source.
|
||||
* 3. Generated and original position, original source, as well as a name
|
||||
* token.
|
||||
*
|
||||
* To maintain consistency, we validate that any new mapping being added falls
|
||||
* in to one of these categories.
|
||||
*/
|
||||
SourceMapGenerator.prototype._validateMapping =
|
||||
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
|
||||
aName) {
|
||||
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
|
||||
&& aGenerated.line > 0 && aGenerated.column >= 0
|
||||
&& !aOriginal && !aSource && !aName) {
|
||||
// Case 1.
|
||||
return;
|
||||
}
|
||||
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
|
||||
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
|
||||
&& aGenerated.line > 0 && aGenerated.column >= 0
|
||||
&& aOriginal.line > 0 && aOriginal.column >= 0
|
||||
&& aSource) {
|
||||
// Cases 2 and 3.
|
||||
return;
|
||||
}
|
||||
else {
|
||||
throw new Error('Invalid mapping.');
|
||||
}
|
||||
};
|
||||
|
||||
function cmpLocation(loc1, loc2) {
|
||||
var cmp = (loc1 && loc1.line) - (loc2 && loc2.line);
|
||||
return cmp ? cmp : (loc1 && loc1.column) - (loc2 && loc2.column);
|
||||
}
|
||||
|
||||
function strcmp(str1, str2) {
|
||||
str1 = str1 || '';
|
||||
str2 = str2 || '';
|
||||
return (str1 > str2) - (str1 < str2);
|
||||
}
|
||||
|
||||
function cmpMapping(mappingA, mappingB) {
|
||||
return cmpLocation(mappingA.generated, mappingB.generated) ||
|
||||
cmpLocation(mappingA.original, mappingB.original) ||
|
||||
strcmp(mappingA.source, mappingB.source) ||
|
||||
strcmp(mappingA.name, mappingB.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the accumulated mappings in to the stream of base 64 VLQs
|
||||
* specified by the source map format.
|
||||
*/
|
||||
SourceMapGenerator.prototype._serializeMappings =
|
||||
function SourceMapGenerator_serializeMappings() {
|
||||
var previousGeneratedColumn = 0;
|
||||
var previousGeneratedLine = 1;
|
||||
var previousOriginalColumn = 0;
|
||||
var previousOriginalLine = 0;
|
||||
var previousName = 0;
|
||||
var previousSource = 0;
|
||||
var result = '';
|
||||
var mapping;
|
||||
|
||||
// The mappings must be guarenteed to be in sorted order before we start
|
||||
// serializing them or else the generated line numbers (which are defined
|
||||
// via the ';' separators) will be all messed up. Note: it might be more
|
||||
// performant to maintain the sorting as we insert them, rather than as we
|
||||
// serialize them, but the big O is the same either way.
|
||||
this._mappings.sort(cmpMapping);
|
||||
|
||||
for (var i = 0, len = this._mappings.length; i < len; i++) {
|
||||
mapping = this._mappings[i];
|
||||
|
||||
if (mapping.generated.line !== previousGeneratedLine) {
|
||||
previousGeneratedColumn = 0;
|
||||
while (mapping.generated.line !== previousGeneratedLine) {
|
||||
result += ';';
|
||||
previousGeneratedLine++;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (i > 0) {
|
||||
if (!cmpMapping(mapping, this._mappings[i - 1])) {
|
||||
continue;
|
||||
}
|
||||
result += ',';
|
||||
}
|
||||
}
|
||||
|
||||
result += base64VLQ.encode(mapping.generated.column
|
||||
- previousGeneratedColumn);
|
||||
previousGeneratedColumn = mapping.generated.column;
|
||||
|
||||
if (mapping.source && mapping.original) {
|
||||
result += base64VLQ.encode(this._sources.indexOf(mapping.source)
|
||||
- previousSource);
|
||||
previousSource = this._sources.indexOf(mapping.source);
|
||||
|
||||
// lines are stored 0-based in SourceMap spec version 3
|
||||
result += base64VLQ.encode(mapping.original.line - 1
|
||||
- previousOriginalLine);
|
||||
previousOriginalLine = mapping.original.line - 1;
|
||||
|
||||
result += base64VLQ.encode(mapping.original.column
|
||||
- previousOriginalColumn);
|
||||
previousOriginalColumn = mapping.original.column;
|
||||
|
||||
if (mapping.name) {
|
||||
result += base64VLQ.encode(this._names.indexOf(mapping.name)
|
||||
- previousName);
|
||||
previousName = this._names.indexOf(mapping.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Externalize the source map.
|
||||
*/
|
||||
SourceMapGenerator.prototype.toJSON =
|
||||
function SourceMapGenerator_toJSON() {
|
||||
var map = {
|
||||
version: this._version,
|
||||
file: this._file,
|
||||
sources: this._sources.toArray(),
|
||||
names: this._names.toArray(),
|
||||
mappings: this._serializeMappings()
|
||||
};
|
||||
if (this._sourceRoot) {
|
||||
map.sourceRoot = this._sourceRoot;
|
||||
}
|
||||
if (this._sourcesContents) {
|
||||
map.sourcesContent = map.sources.map(function (source) {
|
||||
if (map.sourceRoot) {
|
||||
source = util.relative(map.sourceRoot, source);
|
||||
}
|
||||
return Object.prototype.hasOwnProperty.call(
|
||||
this._sourcesContents, util.toSetString(source))
|
||||
? this._sourcesContents[util.toSetString(source)]
|
||||
: null;
|
||||
}, this);
|
||||
}
|
||||
return map;
|
||||
};
|
||||
|
||||
/**
|
||||
* Render the source map being generated to a string.
|
||||
*/
|
||||
SourceMapGenerator.prototype.toString =
|
||||
function SourceMapGenerator_toString() {
|
||||
return JSON.stringify(this);
|
||||
};
|
||||
|
||||
exports.SourceMapGenerator = SourceMapGenerator;
|
||||
|
||||
});
|
|
@ -1,353 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
if (typeof define !== 'function') {
|
||||
var define = require('amdefine')(module);
|
||||
}
|
||||
define(function (require, exports, module) {
|
||||
|
||||
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
|
||||
var util = require('./util');
|
||||
|
||||
/**
|
||||
* SourceNodes provide a way to abstract over interpolating/concatenating
|
||||
* snippets of generated JavaScript source code while maintaining the line and
|
||||
* column information associated with the original source code.
|
||||
*
|
||||
* @param aLine The original line number.
|
||||
* @param aColumn The original column number.
|
||||
* @param aSource The original source's filename.
|
||||
* @param aChunks Optional. An array of strings which are snippets of
|
||||
* generated JS, or other SourceNodes.
|
||||
* @param aName The original identifier.
|
||||
*/
|
||||
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
|
||||
this.children = [];
|
||||
this.sourceContents = {};
|
||||
this.line = aLine === undefined ? null : aLine;
|
||||
this.column = aColumn === undefined ? null : aColumn;
|
||||
this.source = aSource === undefined ? null : aSource;
|
||||
this.name = aName === undefined ? null : aName;
|
||||
if (aChunks != null) this.add(aChunks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a SourceNode from generated code and a SourceMapConsumer.
|
||||
*
|
||||
* @param aGeneratedCode The generated code
|
||||
* @param aSourceMapConsumer The SourceMap for the generated code
|
||||
*/
|
||||
SourceNode.fromStringWithSourceMap =
|
||||
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
|
||||
// The SourceNode we want to fill with the generated code
|
||||
// and the SourceMap
|
||||
var node = new SourceNode();
|
||||
|
||||
// The generated code
|
||||
// Processed fragments are removed from this array.
|
||||
var remainingLines = aGeneratedCode.split('\n');
|
||||
|
||||
// We need to remember the position of "remainingLines"
|
||||
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
|
||||
|
||||
// The generate SourceNodes we need a code range.
|
||||
// To extract it current and last mapping is used.
|
||||
// Here we store the last mapping.
|
||||
var lastMapping = null;
|
||||
|
||||
aSourceMapConsumer.eachMapping(function (mapping) {
|
||||
if (lastMapping === null) {
|
||||
// We add the generated code until the first mapping
|
||||
// to the SourceNode without any mapping.
|
||||
// Each line is added as separate string.
|
||||
while (lastGeneratedLine < mapping.generatedLine) {
|
||||
node.add(remainingLines.shift() + "\n");
|
||||
lastGeneratedLine++;
|
||||
}
|
||||
if (lastGeneratedColumn < mapping.generatedColumn) {
|
||||
var nextLine = remainingLines[0];
|
||||
node.add(nextLine.substr(0, mapping.generatedColumn));
|
||||
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
|
||||
lastGeneratedColumn = mapping.generatedColumn;
|
||||
}
|
||||
} else {
|
||||
// We add the code from "lastMapping" to "mapping":
|
||||
// First check if there is a new line in between.
|
||||
if (lastGeneratedLine < mapping.generatedLine) {
|
||||
var code = "";
|
||||
// Associate full lines with "lastMapping"
|
||||
do {
|
||||
code += remainingLines.shift() + "\n";
|
||||
lastGeneratedLine++;
|
||||
lastGeneratedColumn = 0;
|
||||
} while (lastGeneratedLine < mapping.generatedLine);
|
||||
// When we reached the correct line, we add code until we
|
||||
// reach the correct column too.
|
||||
if (lastGeneratedColumn < mapping.generatedColumn) {
|
||||
var nextLine = remainingLines[0];
|
||||
code += nextLine.substr(0, mapping.generatedColumn);
|
||||
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
|
||||
lastGeneratedColumn = mapping.generatedColumn;
|
||||
}
|
||||
// Create the SourceNode.
|
||||
addMappingWithCode(lastMapping, code);
|
||||
} else {
|
||||
// There is no new line in between.
|
||||
// Associate the code between "lastGeneratedColumn" and
|
||||
// "mapping.generatedColumn" with "lastMapping"
|
||||
var nextLine = remainingLines[0];
|
||||
var code = nextLine.substr(0, mapping.generatedColumn -
|
||||
lastGeneratedColumn);
|
||||
remainingLines[0] = nextLine.substr(mapping.generatedColumn -
|
||||
lastGeneratedColumn);
|
||||
lastGeneratedColumn = mapping.generatedColumn;
|
||||
addMappingWithCode(lastMapping, code);
|
||||
}
|
||||
}
|
||||
lastMapping = mapping;
|
||||
}, this);
|
||||
// We have processed all mappings.
|
||||
// Associate the remaining code in the current line with "lastMapping"
|
||||
// and add the remaining lines without any mapping
|
||||
addMappingWithCode(lastMapping, remainingLines.join("\n"));
|
||||
|
||||
// Copy sourcesContent into SourceNode
|
||||
aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
||||
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
||||
if (content) {
|
||||
node.setSourceContent(sourceFile, content);
|
||||
}
|
||||
});
|
||||
|
||||
return node;
|
||||
|
||||
function addMappingWithCode(mapping, code) {
|
||||
if (mapping.source === undefined) {
|
||||
node.add(code);
|
||||
} else {
|
||||
node.add(new SourceNode(mapping.originalLine,
|
||||
mapping.originalColumn,
|
||||
mapping.source,
|
||||
code,
|
||||
mapping.name));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a chunk of generated JS to this source node.
|
||||
*
|
||||
* @param aChunk A string snippet of generated JS code, another instance of
|
||||
* SourceNode, or an array where each member is one of those things.
|
||||
*/
|
||||
SourceNode.prototype.add = function SourceNode_add(aChunk) {
|
||||
if (Array.isArray(aChunk)) {
|
||||
aChunk.forEach(function (chunk) {
|
||||
this.add(chunk);
|
||||
}, this);
|
||||
}
|
||||
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
|
||||
if (aChunk) {
|
||||
this.children.push(aChunk);
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new TypeError(
|
||||
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
|
||||
);
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a chunk of generated JS to the beginning of this source node.
|
||||
*
|
||||
* @param aChunk A string snippet of generated JS code, another instance of
|
||||
* SourceNode, or an array where each member is one of those things.
|
||||
*/
|
||||
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
|
||||
if (Array.isArray(aChunk)) {
|
||||
for (var i = aChunk.length-1; i >= 0; i--) {
|
||||
this.prepend(aChunk[i]);
|
||||
}
|
||||
}
|
||||
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
|
||||
this.children.unshift(aChunk);
|
||||
}
|
||||
else {
|
||||
throw new TypeError(
|
||||
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
|
||||
);
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Walk over the tree of JS snippets in this node and its children. The
|
||||
* walking function is called once for each snippet of JS and is passed that
|
||||
* snippet and the its original associated source's line/column location.
|
||||
*
|
||||
* @param aFn The traversal function.
|
||||
*/
|
||||
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
|
||||
this.children.forEach(function (chunk) {
|
||||
if (chunk instanceof SourceNode) {
|
||||
chunk.walk(aFn);
|
||||
}
|
||||
else {
|
||||
if (chunk !== '') {
|
||||
aFn(chunk, { source: this.source,
|
||||
line: this.line,
|
||||
column: this.column,
|
||||
name: this.name });
|
||||
}
|
||||
}
|
||||
}, this);
|
||||
};
|
||||
|
||||
/**
|
||||
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
|
||||
* each of `this.children`.
|
||||
*
|
||||
* @param aSep The separator.
|
||||
*/
|
||||
SourceNode.prototype.join = function SourceNode_join(aSep) {
|
||||
var newChildren;
|
||||
var i;
|
||||
var len = this.children.length;
|
||||
if (len > 0) {
|
||||
newChildren = [];
|
||||
for (i = 0; i < len-1; i++) {
|
||||
newChildren.push(this.children[i]);
|
||||
newChildren.push(aSep);
|
||||
}
|
||||
newChildren.push(this.children[i]);
|
||||
this.children = newChildren;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Call String.prototype.replace on the very right-most source snippet. Useful
|
||||
* for trimming whitespace from the end of a source node, etc.
|
||||
*
|
||||
* @param aPattern The pattern to replace.
|
||||
* @param aReplacement The thing to replace the pattern with.
|
||||
*/
|
||||
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
|
||||
var lastChild = this.children[this.children.length - 1];
|
||||
if (lastChild instanceof SourceNode) {
|
||||
lastChild.replaceRight(aPattern, aReplacement);
|
||||
}
|
||||
else if (typeof lastChild === 'string') {
|
||||
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
|
||||
}
|
||||
else {
|
||||
this.children.push(''.replace(aPattern, aReplacement));
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the source content for a source file. This will be added to the SourceMapGenerator
|
||||
* in the sourcesContent field.
|
||||
*
|
||||
* @param aSourceFile The filename of the source file
|
||||
* @param aSourceContent The content of the source file
|
||||
*/
|
||||
SourceNode.prototype.setSourceContent =
|
||||
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
|
||||
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
|
||||
};
|
||||
|
||||
/**
|
||||
* Walk over the tree of SourceNodes. The walking function is called for each
|
||||
* source file content and is passed the filename and source content.
|
||||
*
|
||||
* @param aFn The traversal function.
|
||||
*/
|
||||
SourceNode.prototype.walkSourceContents =
|
||||
function SourceNode_walkSourceContents(aFn) {
|
||||
this.children.forEach(function (chunk) {
|
||||
if (chunk instanceof SourceNode) {
|
||||
chunk.walkSourceContents(aFn);
|
||||
}
|
||||
}, this);
|
||||
Object.keys(this.sourceContents).forEach(function (sourceFileKey) {
|
||||
aFn(util.fromSetString(sourceFileKey), this.sourceContents[sourceFileKey]);
|
||||
}, this);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the string representation of this source node. Walks over the tree
|
||||
* and concatenates all the various snippets together to one string.
|
||||
*/
|
||||
SourceNode.prototype.toString = function SourceNode_toString() {
|
||||
var str = "";
|
||||
this.walk(function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
return str;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the string representation of this source node along with a source
|
||||
* map.
|
||||
*/
|
||||
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
|
||||
var generated = {
|
||||
code: "",
|
||||
line: 1,
|
||||
column: 0
|
||||
};
|
||||
var map = new SourceMapGenerator(aArgs);
|
||||
var sourceMappingActive = false;
|
||||
this.walk(function (chunk, original) {
|
||||
generated.code += chunk;
|
||||
if (original.source !== null
|
||||
&& original.line !== null
|
||||
&& original.column !== null) {
|
||||
map.addMapping({
|
||||
source: original.source,
|
||||
original: {
|
||||
line: original.line,
|
||||
column: original.column
|
||||
},
|
||||
generated: {
|
||||
line: generated.line,
|
||||
column: generated.column
|
||||
},
|
||||
name: original.name
|
||||
});
|
||||
sourceMappingActive = true;
|
||||
} else if (sourceMappingActive) {
|
||||
map.addMapping({
|
||||
generated: {
|
||||
line: generated.line,
|
||||
column: generated.column
|
||||
}
|
||||
});
|
||||
sourceMappingActive = false;
|
||||
}
|
||||
chunk.split('').forEach(function (ch) {
|
||||
if (ch === '\n') {
|
||||
generated.line++;
|
||||
generated.column = 0;
|
||||
} else {
|
||||
generated.column++;
|
||||
}
|
||||
});
|
||||
});
|
||||
this.walkSourceContents(function (sourceFile, sourceContent) {
|
||||
map.setSourceContent(sourceFile, sourceContent);
|
||||
});
|
||||
|
||||
return { code: generated.code, map: map };
|
||||
};
|
||||
|
||||
exports.SourceNode = SourceNode;
|
||||
|
||||
});
|
|
@ -1,91 +0,0 @@
|
|||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
if (typeof define !== 'function') {
|
||||
var define = require('amdefine')(module);
|
||||
}
|
||||
define(function (require, exports, module) {
|
||||
|
||||
/**
|
||||
* This is a helper function for getting values from parameter/options
|
||||
* objects.
|
||||
*
|
||||
* @param args The object we are extracting values from
|
||||
* @param name The name of the property we are getting.
|
||||
* @param defaultValue An optional value to return if the property is missing
|
||||
* from the object. If this is not specified and the property is missing, an
|
||||
* error will be thrown.
|
||||
*/
|
||||
function getArg(aArgs, aName, aDefaultValue) {
|
||||
if (aName in aArgs) {
|
||||
return aArgs[aName];
|
||||
} else if (arguments.length === 3) {
|
||||
return aDefaultValue;
|
||||
} else {
|
||||
throw new Error('"' + aName + '" is a required argument.');
|
||||
}
|
||||
}
|
||||
exports.getArg = getArg;
|
||||
|
||||
var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
|
||||
|
||||
function urlParse(aUrl) {
|
||||
var match = aUrl.match(urlRegexp);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
scheme: match[1],
|
||||
auth: match[3],
|
||||
host: match[4],
|
||||
port: match[6],
|
||||
path: match[7]
|
||||
};
|
||||
}
|
||||
|
||||
function join(aRoot, aPath) {
|
||||
var url;
|
||||
|
||||
if (aPath.match(urlRegexp)) {
|
||||
return aPath;
|
||||
}
|
||||
|
||||
if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
|
||||
return aRoot.replace(url.path, '') + aPath;
|
||||
}
|
||||
|
||||
return aRoot.replace(/\/$/, '') + '/' + aPath;
|
||||
}
|
||||
exports.join = join;
|
||||
|
||||
/**
|
||||
* Because behavior goes wacky when you set `__proto__` on objects, we
|
||||
* have to prefix all the strings in our set with an arbitrary character.
|
||||
*
|
||||
* See https://github.com/mozilla/source-map/pull/31 and
|
||||
* https://github.com/mozilla/source-map/issues/30
|
||||
*
|
||||
* @param String aStr
|
||||
*/
|
||||
function toSetString(aStr) {
|
||||
return '$' + aStr;
|
||||
}
|
||||
exports.toSetString = toSetString;
|
||||
|
||||
function fromSetString(aStr) {
|
||||
return aStr.substr(1);
|
||||
}
|
||||
exports.fromSetString = fromSetString;
|
||||
|
||||
function relative(aRoot, aPath) {
|
||||
aRoot = aRoot.replace(/\/$/, '');
|
||||
return aPath.indexOf(aRoot + '/') === 0
|
||||
? aPath.substr(aRoot.length + 1)
|
||||
: aPath;
|
||||
}
|
||||
exports.relative = relative;
|
||||
|
||||
});
|
|
@ -1 +0,0 @@
|
|||
tests/
|
|
@ -1,58 +0,0 @@
|
|||
amdefine is released under two licenses: new BSD, and MIT. You may pick the
|
||||
license that best suits your development needs. The text of both licenses are
|
||||
provided below.
|
||||
|
||||
|
||||
The "New" BSD License:
|
||||
----------------------
|
||||
|
||||
Copyright (c) 2011, The Dojo Foundation
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of the Dojo Foundation nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
|
||||
MIT License
|
||||
-----------
|
||||
|
||||
Copyright (c) 2011, The Dojo Foundation
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
|
@ -1,119 +0,0 @@
|
|||
# amdefine
|
||||
|
||||
A module that can be used to implement AMD's define() in Node. This allows you
|
||||
to code to the AMD API and have the module work in node programs without
|
||||
requiring those other programs to use AMD.
|
||||
|
||||
## Usage
|
||||
|
||||
**1)** Update your package.json to indicate amdefine as a dependency:
|
||||
|
||||
```javascript
|
||||
"dependencies": {
|
||||
"amdefine": ">=0.0.2"
|
||||
}
|
||||
```
|
||||
|
||||
Then run `npm install` to get amdefine into your project.
|
||||
|
||||
**2)** At the top of each module that uses define(), place this code:
|
||||
|
||||
```javascript
|
||||
if (typeof define !== 'function') { var define = require('amdefine')(module) }
|
||||
```
|
||||
|
||||
**Only use these snippets** when loading amdefine. If you preserve the basic structure,
|
||||
with the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer).
|
||||
|
||||
You can add spaces, line breaks and even require amdefine with a local path, but
|
||||
keep the rest of the structure to get the stripping behavior.
|
||||
|
||||
As you may know, because `if` statements in JavaScript don't have their own scope, the var
|
||||
declaration in the above snippet is made whether the `if` expression is truthy or not. If
|
||||
RequireJS is loaded then the declaration is superfluous because `define` is already already
|
||||
declared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var`
|
||||
declarations of the same variable in the same scope gracefully.
|
||||
|
||||
If you want to deliver amdefine.js with your code rather than specifying it as a dependency
|
||||
with npm, then just download the latest release and refer to it using a relative path:
|
||||
|
||||
[Version 0.0.2](https://github.com/jrburke/amdefine/raw/0.0.2/amdefine.js)
|
||||
|
||||
## define() usage
|
||||
|
||||
It is best if you use the anonymous forms of define() in your module:
|
||||
|
||||
```javascript
|
||||
define(function (require) {
|
||||
var dependency = require('dependency');
|
||||
});
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```javascript
|
||||
define(['dependency'], function (dependency) {
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
## RequireJS optimizer integration. <a name="optimizer"></name>
|
||||
|
||||
Version 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html)
|
||||
will have support for stripping the `if (typeof define !== 'function')` check
|
||||
mentioned above, so you can include this snippet for code that runs in the
|
||||
browser, but avoid taking the cost of the if() statement once the code is
|
||||
optimized for deployment.
|
||||
|
||||
## Node 0.4 Support
|
||||
|
||||
If you want to support Node 0.4, then add `require` as the second parameter to amdefine:
|
||||
|
||||
```javascript
|
||||
//Only if you want Node 0.4. If using 0.5 or later, use the above snippet.
|
||||
if (typeof define !== 'function') { var define = require('amdefine')(module, require) }
|
||||
```
|
||||
|
||||
## Limitations
|
||||
|
||||
### Synchronous vs Asynchronous
|
||||
|
||||
amdefine creates a define() function that is callable by your code. It will
|
||||
execute and trace dependencies and call the factory function *synchronously*,
|
||||
to keep the behavior in line with Node's synchronous dependency tracing.
|
||||
|
||||
The exception: calling AMD's callback-style require() from inside a factory
|
||||
function. The require callback is called on process.nextTick():
|
||||
|
||||
```javascript
|
||||
define(function (require) {
|
||||
require(['a'], function(a) {
|
||||
//'a' is loaded synchronously, but
|
||||
//this callback is called on process.nextTick().
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Loader Plugins
|
||||
|
||||
Loader plugins are supported as long as they call their load() callbacks
|
||||
synchronously. So ones that do network requests will not work. However plugins
|
||||
like [text](http://requirejs.org/docs/api.html#text) can load text files locally.
|
||||
|
||||
The plugin API's `load.fromText()` is **not supported** in amdefine, so this means
|
||||
transpiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs)
|
||||
will not work. This may be fixable, but it is a bit complex, and I do not have
|
||||
enough node-fu to figure it out yet. See the source for amdefine.js if you want
|
||||
to get an idea of the issues involved.
|
||||
|
||||
## Tests
|
||||
|
||||
To run the tests, cd to **tests** and run:
|
||||
|
||||
```
|
||||
node all.js
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
New BSD and MIT. Check the LICENSE file for all the details.
|
|
@ -1,299 +0,0 @@
|
|||
/** vim: et:ts=4:sw=4:sts=4
|
||||
* @license amdefine 0.0.4 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
|
||||
* Available via the MIT or new BSD license.
|
||||
* see: http://github.com/jrburke/amdefine for details
|
||||
*/
|
||||
|
||||
/*jslint node: true */
|
||||
/*global module, process */
|
||||
'use strict';
|
||||
|
||||
var path = require('path');
|
||||
|
||||
/**
|
||||
* Creates a define for node.
|
||||
* @param {Object} module the "module" object that is defined by Node for the
|
||||
* current module.
|
||||
* @param {Function} [require]. Node's require function for the current module.
|
||||
* It only needs to be passed in Node versions before 0.5, when module.require
|
||||
* did not exist.
|
||||
* @returns {Function} a define function that is usable for the current node
|
||||
* module.
|
||||
*/
|
||||
function amdefine(module, require) {
|
||||
var defineCache = {},
|
||||
loaderCache = {},
|
||||
alreadyCalled = false,
|
||||
makeRequire, stringRequire;
|
||||
|
||||
/**
|
||||
* Trims the . and .. from an array of path segments.
|
||||
* It will keep a leading path segment if a .. will become
|
||||
* the first path segment, to help with module name lookups,
|
||||
* which act like paths, but can be remapped. But the end result,
|
||||
* all paths that use this function should look normalized.
|
||||
* NOTE: this method MODIFIES the input array.
|
||||
* @param {Array} ary the array of path segments.
|
||||
*/
|
||||
function trimDots(ary) {
|
||||
var i, part;
|
||||
for (i = 0; ary[i]; i+= 1) {
|
||||
part = ary[i];
|
||||
if (part === '.') {
|
||||
ary.splice(i, 1);
|
||||
i -= 1;
|
||||
} else if (part === '..') {
|
||||
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
|
||||
//End of the line. Keep at least one non-dot
|
||||
//path segment at the front so it can be mapped
|
||||
//correctly to disk. Otherwise, there is likely
|
||||
//no path mapping for a path starting with '..'.
|
||||
//This can still fail, but catches the most reasonable
|
||||
//uses of ..
|
||||
break;
|
||||
} else if (i > 0) {
|
||||
ary.splice(i - 1, 2);
|
||||
i -= 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalize(name, baseName) {
|
||||
var baseParts;
|
||||
|
||||
//Adjust any relative paths.
|
||||
if (name && name.charAt(0) === '.') {
|
||||
//If have a base name, try to normalize against it,
|
||||
//otherwise, assume it is a top-level require that will
|
||||
//be relative to baseUrl in the end.
|
||||
if (baseName) {
|
||||
baseParts = baseName.split('/');
|
||||
baseParts = baseParts.slice(0, baseParts.length - 1);
|
||||
baseParts = baseParts.concat(name.split('/'));
|
||||
trimDots(baseParts);
|
||||
name = baseParts.join('/');
|
||||
}
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the normalize() function passed to a loader plugin's
|
||||
* normalize method.
|
||||
*/
|
||||
function makeNormalize(relName) {
|
||||
return function (name) {
|
||||
return normalize(name, relName);
|
||||
};
|
||||
}
|
||||
|
||||
function makeLoad(id) {
|
||||
function load(value) {
|
||||
loaderCache[id] = value;
|
||||
}
|
||||
|
||||
load.fromText = function (id, text) {
|
||||
//This one is difficult because the text can/probably uses
|
||||
//define, and any relative paths and requires should be relative
|
||||
//to that id was it would be found on disk. But this would require
|
||||
//bootstrapping a module/require fairly deeply from node core.
|
||||
//Not sure how best to go about that yet.
|
||||
throw new Error('amdefine does not implement load.fromText');
|
||||
};
|
||||
|
||||
return load;
|
||||
}
|
||||
|
||||
makeRequire = function (systemRequire, exports, module, relId) {
|
||||
function amdRequire(deps, callback) {
|
||||
if (typeof deps === 'string') {
|
||||
//Synchronous, single module require('')
|
||||
return stringRequire(systemRequire, exports, module, deps, relId);
|
||||
} else {
|
||||
//Array of dependencies with a callback.
|
||||
|
||||
//Convert the dependencies to modules.
|
||||
deps = deps.map(function (depName) {
|
||||
return stringRequire(systemRequire, exports, module, depName, relId);
|
||||
});
|
||||
|
||||
//Wait for next tick to call back the require call.
|
||||
process.nextTick(function () {
|
||||
callback.apply(null, deps);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
amdRequire.toUrl = function (filePath) {
|
||||
if (filePath.indexOf('.') === 0) {
|
||||
return normalize(filePath, path.dirname(module.filename));
|
||||
} else {
|
||||
return filePath;
|
||||
}
|
||||
};
|
||||
|
||||
return amdRequire;
|
||||
};
|
||||
|
||||
//Favor explicit value, passed in if the module wants to support Node 0.4.
|
||||
require = require || function req() {
|
||||
return module.require.apply(module, arguments);
|
||||
};
|
||||
|
||||
function runFactory(id, deps, factory) {
|
||||
var r, e, m, result;
|
||||
|
||||
if (id) {
|
||||
e = loaderCache[id] = {};
|
||||
m = {
|
||||
id: id,
|
||||
uri: __filename,
|
||||
exports: e
|
||||
};
|
||||
r = makeRequire(undefined, e, m, id);
|
||||
} else {
|
||||
//Only support one define call per file
|
||||
if (alreadyCalled) {
|
||||
throw new Error('amdefine with no module ID cannot be called more than once per file.');
|
||||
}
|
||||
alreadyCalled = true;
|
||||
|
||||
//Use the real variables from node
|
||||
//Use module.exports for exports, since
|
||||
//the exports in here is amdefine exports.
|
||||
e = module.exports;
|
||||
m = module;
|
||||
r = makeRequire(require, e, m, module.id);
|
||||
}
|
||||
|
||||
//If there are dependencies, they are strings, so need
|
||||
//to convert them to dependency values.
|
||||
if (deps) {
|
||||
deps = deps.map(function (depName) {
|
||||
return r(depName);
|
||||
});
|
||||
}
|
||||
|
||||
//Call the factory with the right dependencies.
|
||||
if (typeof factory === 'function') {
|
||||
result = factory.apply(module.exports, deps);
|
||||
} else {
|
||||
result = factory;
|
||||
}
|
||||
|
||||
if (result !== undefined) {
|
||||
m.exports = result;
|
||||
if (id) {
|
||||
loaderCache[id] = m.exports;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stringRequire = function (systemRequire, exports, module, id, relId) {
|
||||
//Split the ID by a ! so that
|
||||
var index = id.indexOf('!'),
|
||||
originalId = id,
|
||||
prefix, plugin;
|
||||
|
||||
if (index === -1) {
|
||||
id = normalize(id, relId);
|
||||
|
||||
//Straight module lookup. If it is one of the special dependencies,
|
||||
//deal with it, otherwise, delegate to node.
|
||||
if (id === 'require') {
|
||||
return makeRequire(systemRequire, exports, module, relId);
|
||||
} else if (id === 'exports') {
|
||||
return exports;
|
||||
} else if (id === 'module') {
|
||||
return module;
|
||||
} else if (loaderCache.hasOwnProperty(id)) {
|
||||
return loaderCache[id];
|
||||
} else if (defineCache[id]) {
|
||||
runFactory.apply(null, defineCache[id]);
|
||||
return loaderCache[id];
|
||||
} else {
|
||||
if(systemRequire) {
|
||||
return systemRequire(originalId);
|
||||
} else {
|
||||
throw new Error('No module with ID: ' + id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//There is a plugin in play.
|
||||
prefix = id.substring(0, index);
|
||||
id = id.substring(index + 1, id.length);
|
||||
|
||||
plugin = stringRequire(systemRequire, exports, module, prefix, relId);
|
||||
|
||||
if (plugin.normalize) {
|
||||
id = plugin.normalize(id, makeNormalize(relId));
|
||||
} else {
|
||||
//Normalize the ID normally.
|
||||
id = normalize(id, relId);
|
||||
}
|
||||
|
||||
if (loaderCache[id]) {
|
||||
return loaderCache[id];
|
||||
} else {
|
||||
plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
|
||||
|
||||
return loaderCache[id];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//Create a define function specific to the module asking for amdefine.
|
||||
function define(id, deps, factory) {
|
||||
if (Array.isArray(id)) {
|
||||
factory = deps;
|
||||
deps = id;
|
||||
id = undefined;
|
||||
} else if (typeof id !== 'string') {
|
||||
factory = id;
|
||||
id = deps = undefined;
|
||||
}
|
||||
|
||||
if (deps && !Array.isArray(deps)) {
|
||||
factory = deps;
|
||||
deps = undefined;
|
||||
}
|
||||
|
||||
if (!deps) {
|
||||
deps = ['require', 'exports', 'module'];
|
||||
}
|
||||
|
||||
//Set up properties for this module. If an ID, then use
|
||||
//internal cache. If no ID, then use the external variables
|
||||
//for this node module.
|
||||
if (id) {
|
||||
//Put the module in deep freeze until there is a
|
||||
//require call for it.
|
||||
defineCache[id] = [id, deps, factory];
|
||||
} else {
|
||||
runFactory(id, deps, factory);
|
||||
}
|
||||
}
|
||||
|
||||
//define.require, which has access to all the values in the
|
||||
//cache. Useful for AMD modules that all have IDs in the file,
|
||||
//but need to finally export a value to node based on one of those
|
||||
//IDs.
|
||||
define.require = function (id) {
|
||||
if (loaderCache[id]) {
|
||||
return loaderCache[id];
|
||||
}
|
||||
|
||||
if (defineCache[id]) {
|
||||
runFactory.apply(null, defineCache[id]);
|
||||
return loaderCache[id];
|
||||
}
|
||||
};
|
||||
|
||||
define.amd = {};
|
||||
|
||||
return define;
|
||||
}
|
||||
|
||||
module.exports = amdefine;
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue