lirongchuan
parent
cf20a313b3
commit
b2d0dbbe36
@ -0,0 +1,41 @@
|
||||
var createError = require('http-errors');
|
||||
var express = require('express');
|
||||
var path = require('path');
|
||||
var cookieParser = require('cookie-parser');
|
||||
var logger = require('morgan');
|
||||
|
||||
var indexRouter = require('./routes/index');
|
||||
var usersRouter = require('./routes/users');
|
||||
|
||||
var app = express();
|
||||
|
||||
// view engine setup
|
||||
app.set('views', path.join(__dirname, 'views'));
|
||||
app.set('view engine', 'jade');
|
||||
|
||||
app.use(logger('dev'));
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: false }));
|
||||
app.use(cookieParser());
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
|
||||
app.use('/', indexRouter);
|
||||
app.use('/users', usersRouter);
|
||||
|
||||
// catch 404 and forward to error handler
|
||||
app.use(function(req, res, next) {
|
||||
next(createError(404));
|
||||
});
|
||||
|
||||
// error handler
|
||||
app.use(function(err, req, res, next) {
|
||||
// set locals, only providing error in development
|
||||
res.locals.message = err.message;
|
||||
res.locals.error = req.app.get('env') === 'development' ? err : {};
|
||||
|
||||
// render the error page
|
||||
res.status(err.status || 500);
|
||||
res.render('error');
|
||||
});
|
||||
|
||||
module.exports = app;
|
||||
@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var app = require('../app');
|
||||
var debug = require('debug')('workserver:server');
|
||||
var http = require('http');
|
||||
|
||||
/**
|
||||
* Get port from environment and store in Express.
|
||||
*/
|
||||
|
||||
var port = normalizePort(process.env.PORT || '3000');
|
||||
app.set('port', port);
|
||||
|
||||
/**
|
||||
* Create HTTP server.
|
||||
*/
|
||||
|
||||
var server = http.createServer(app);
|
||||
|
||||
/**
|
||||
* Listen on provided port, on all network interfaces.
|
||||
*/
|
||||
|
||||
server.listen(port);
|
||||
server.on('error', onError);
|
||||
server.on('listening', onListening);
|
||||
|
||||
/**
|
||||
* Normalize a port into a number, string, or false.
|
||||
*/
|
||||
|
||||
function normalizePort(val) {
|
||||
var port = parseInt(val, 10);
|
||||
|
||||
if (isNaN(port)) {
|
||||
// named pipe
|
||||
return val;
|
||||
}
|
||||
|
||||
if (port >= 0) {
|
||||
// port number
|
||||
return port;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event listener for HTTP server "error" event.
|
||||
*/
|
||||
|
||||
function onError(error) {
|
||||
if (error.syscall !== 'listen') {
|
||||
throw error;
|
||||
}
|
||||
|
||||
var bind = typeof port === 'string'
|
||||
? 'Pipe ' + port
|
||||
: 'Port ' + port;
|
||||
|
||||
// handle specific listen errors with friendly messages
|
||||
switch (error.code) {
|
||||
case 'EACCES':
|
||||
console.error(bind + ' requires elevated privileges');
|
||||
process.exit(1);
|
||||
break;
|
||||
case 'EADDRINUSE':
|
||||
console.error(bind + ' is already in use');
|
||||
process.exit(1);
|
||||
break;
|
||||
default:
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Event listener for HTTP server "listening" event.
|
||||
*/
|
||||
|
||||
function onListening() {
|
||||
var addr = server.address();
|
||||
var bind = typeof addr === 'string'
|
||||
? 'pipe ' + addr
|
||||
: 'port ' + addr.port;
|
||||
debug('Listening on ' + bind);
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
const configs = {
|
||||
mysql: {
|
||||
host: '118.195.213.51',
|
||||
port: '3306',
|
||||
user: 'root',
|
||||
password: '123456', // 自己设置的密码
|
||||
database: 'expressFrame' // 数据库的名字
|
||||
},
|
||||
// 打印错误
|
||||
log: {
|
||||
error (message) {
|
||||
console.log('[knex error]', message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = configs
|
||||
|
||||
@ -0,0 +1,104 @@
|
||||
// 引用团队模版数据
|
||||
const Team = require('../model/team');
|
||||
|
||||
const teamController = {
|
||||
// showTeam 获取团队数据并返回到页面
|
||||
showTeam: async function(req,res,next){
|
||||
try{
|
||||
let teamData;
|
||||
if(req.query.userId){
|
||||
console.log(req.query.id)
|
||||
teamData= await Team.getById('userId',req.query.userId)
|
||||
}else{
|
||||
teamData = await Team.all()
|
||||
}
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "操作成功",
|
||||
data: teamData
|
||||
})
|
||||
}catch(e){
|
||||
res.json({ code: 0, message: "操作失败", data: e })
|
||||
}
|
||||
},
|
||||
// 新增团队
|
||||
addTeam: async function(req, res, next) {
|
||||
try {
|
||||
const teamData = req.body; // 从请求中获取团队数据
|
||||
|
||||
const result = await Team.insert(teamData);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "团队添加成功",
|
||||
data: result
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "团队添加失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
// 修改团队
|
||||
updateTeam: async function(req, res, next) {
|
||||
try {
|
||||
const id = req.body.id; // Assuming the team ID is passed as a parameter
|
||||
const teamData = req.body; // Updated team data
|
||||
console.log(id + " & " + JSON.stringify(teamData));
|
||||
const result = await Team.update(id, teamData); // Use an appropriate function to update the team
|
||||
if (result) {
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "团队修改成功",
|
||||
data: result
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
code: 404,
|
||||
message: "团队不存在",
|
||||
data: null
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "团队修改失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// 删除团队
|
||||
deleteTeam: async function(req, res, next) {
|
||||
try {
|
||||
const teamId = req.body.teamId; // Assuming the team ID is passed as a parameter
|
||||
const result = await Team.delete(teamId); // Use an appropriate function to delete the team
|
||||
if (result) {
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "团队删除成功",
|
||||
data: result
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
code: 404,
|
||||
message: "团队不存在",
|
||||
data: null
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "团队删除失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
module.exports = teamController;
|
||||
|
||||
@ -0,0 +1,155 @@
|
||||
// 引用用户模版数据
|
||||
const User = require('../model/user');
|
||||
|
||||
const userController = {
|
||||
// showUser 获取用户数据并返回到页面
|
||||
showUser: async function(req,res,next){
|
||||
try{
|
||||
let userData;
|
||||
if(req.query.id){
|
||||
console.log(req.query.id)
|
||||
userData= await User.getById('id',req.query.id)
|
||||
}else{
|
||||
userData = await User.all()
|
||||
}
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "操作成功",
|
||||
data: userData
|
||||
})
|
||||
}catch(e){
|
||||
res.json({ code: 0, message: "操作失败", data: e })
|
||||
}
|
||||
},
|
||||
// 新增用户
|
||||
addUser: async function(req, res, next) {
|
||||
try {
|
||||
const userData = req.body; // 从请求中获取用户数据
|
||||
|
||||
const result = await User.insert(userData);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "用户添加成功",
|
||||
data: result
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "用户添加失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
// 修改用户
|
||||
updateUser: async function(req, res, next) {
|
||||
try {
|
||||
const userId = req.body.id; // Assuming the user ID is passed as a parameter
|
||||
const userData = req.body; // Updated user data
|
||||
console.log(userId + " & " + JSON.stringify(userData));
|
||||
const result = await User.update(userId, userData); // Use an appropriate function to update the user
|
||||
if (result) {
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "用户修改成功",
|
||||
data: result
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
code: 404,
|
||||
message: "用户不存在",
|
||||
data: null
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "用户修改失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
// 删除用户
|
||||
deleteUser: async function(req, res, next) {
|
||||
try {
|
||||
const userId = req.body.id; // Assuming the user ID is passed as a parameter
|
||||
if(userId) {
|
||||
const result = await User.delete(userId); // Use an appropriate function to delete the user
|
||||
}
|
||||
else{
|
||||
const result = await User.deleteAll(); // Use an appropriate function to delete the user
|
||||
}
|
||||
if (result) {
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "用户删除成功",
|
||||
data: result
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
code: 404,
|
||||
message: "用户不存在",
|
||||
data: null
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "用户删除失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
// 注册用户
|
||||
register: async function(req, res, next) {
|
||||
try {
|
||||
const userData = req.body; // 从请求中获取用户数据
|
||||
const newUser = await User.insert(userData); // 创建新用户,使用合适的方法
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "注册成功",
|
||||
data: newUser
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "注册失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// 用户登录
|
||||
login: async function(req, res, next) {
|
||||
try {
|
||||
const user = await User.getById('username',req.body.username);// 根据邮箱和密码查找用户,使用合适的方法
|
||||
console.log(req.body.password+" & "+JSON.stringify(user)+" & "+req.body.username);
|
||||
if (user.length==0||req.body.password!== user[0].password) {
|
||||
res.json({
|
||||
code: 401,
|
||||
message: "登录失败,用户名或密码不正确",
|
||||
data: null
|
||||
});
|
||||
} else {
|
||||
// 在此处可以生成并返回一个 JSON Web Token (JWT) 作为用户的身份认证标识
|
||||
const token = await User.generateAuthToken();
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "登录成功",
|
||||
data: { user, token }
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "登录失败",
|
||||
data: e.toString()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
module.exports = userController;
|
||||
|
||||
@ -0,0 +1,104 @@
|
||||
|
||||
const Work = require('../model/work');
|
||||
|
||||
const workController = {
|
||||
// showWork 获取工作数据并返回到页面
|
||||
showWork: async function(req,res,next){
|
||||
try{
|
||||
let workData;
|
||||
if(req.query.id){
|
||||
console.log(req.query.id)
|
||||
workData= await Work.getById('id',req.query.id)
|
||||
}else{
|
||||
workData = await Work.all()
|
||||
}
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "操作成功",
|
||||
data: workData
|
||||
})
|
||||
}catch(e){
|
||||
res.json({ code: 0, message: "操作失败", data: e })
|
||||
}
|
||||
},
|
||||
// 新增工作
|
||||
addWork: async function(req, res, next) {
|
||||
try {
|
||||
const workData = req.body; // 从请求中获取工作数据
|
||||
|
||||
const result = await Work.insert(workData);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "工作添加成功",
|
||||
data: result
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "工作添加失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
// 修改工作
|
||||
updateWork: async function(req, res, next) {
|
||||
try {
|
||||
const workId = req.body.id; // Assuming the work ID is passed as a parameter
|
||||
const workData = req.body; // Updated work data
|
||||
console.log(workId + " & " + JSON.stringify(workData));
|
||||
const result = await Work.update(workId, workData); // Use an appropriate function to update the work
|
||||
if (result) {
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "工作修改成功",
|
||||
data: result
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
code: 404,
|
||||
message: "工作不存在",
|
||||
data: null
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "工作修改失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// 删除工作
|
||||
deleteWork: async function(req, res, next) {
|
||||
try {
|
||||
const workId = req.body.id; // Assuming the work ID is passed as a parameter
|
||||
const result = await Work.delete(workId); // Use an appropriate function to delete the work
|
||||
if (result) {
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "工作删除成功",
|
||||
data: result
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
code: 404,
|
||||
message: "工作不存在",
|
||||
data: null
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "工作删除失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
module.exports = workController;
|
||||
|
||||
@ -0,0 +1,165 @@
|
||||
const Course = require('../../model/xah/course');
|
||||
const {spawn}=require('child_process');
|
||||
const path = require('path');
|
||||
const courseController = {
|
||||
|
||||
// 展示一个课程的详细内容
|
||||
showOneCourse: async function(req,res,next){
|
||||
try{
|
||||
const id=req.body.id;
|
||||
console.log(id);
|
||||
let courseData = await Course.selectOne(id);
|
||||
console.log(courseData);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "操作成功",
|
||||
data: courseData
|
||||
})
|
||||
}catch(e){
|
||||
res.json({ code: 0, message: "操作失败", data: e })
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
// 展示(一个)用户的所有课程
|
||||
showCourse: async function(req,res,next){
|
||||
try{
|
||||
const userId=req.body.userId;
|
||||
//let courseData = await Course.getCourseByUserId(userId)
|
||||
let courseData = await Course.all();
|
||||
console.log(courseData);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "操作成功",
|
||||
data: courseData
|
||||
})
|
||||
}catch(e){
|
||||
res.json({ code: 0, message: "操作失败", data: e })
|
||||
}
|
||||
},
|
||||
// 给某个用户新增一个课程
|
||||
addCourse: async function(req, res, next) {
|
||||
try {
|
||||
const courseData = req.body; // 从请求中获取用户数据
|
||||
console.log(courseData);
|
||||
const result = await Course.insert(courseData);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "课程添加成功",
|
||||
data: result
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "课程添加失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
//修改课程内容
|
||||
updateCourse: async function(req, res, next) {
|
||||
try {
|
||||
const courseData = req.body; // 从请求中获取用户数据
|
||||
const result = await Course.update(courseData.id,courseData);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "课程修改成功",
|
||||
data: courseData
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "课程修改失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
//删除课程内容
|
||||
deleteCourse: async function(req, res, next) {
|
||||
try {
|
||||
const id = req.body.id; // 从请求中获取用户数据
|
||||
const result = await Course.delete(id);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "课程删除成功",
|
||||
data: result
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "课程删除失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
//爬取学校课程相关的信息并返回
|
||||
getAllCourse:async function(req, res, next) {
|
||||
try {
|
||||
let info = req.body;
|
||||
//let userid = info.userId;
|
||||
const passwd = info.passwd;
|
||||
const year = info.year;
|
||||
const term = info.term;
|
||||
console.log(info);
|
||||
//console.log(userid);
|
||||
console.log(passwd);
|
||||
console.log(year);
|
||||
console.log(term);
|
||||
|
||||
//定位到脚本的位置
|
||||
const pythonScriptPath = path.join(__dirname,'..', '..', 'utils', 'getCourse', 'getSchedule.py');
|
||||
|
||||
//用子进程执行代码
|
||||
const pythonProcess = spawn('python', [pythonScriptPath]);
|
||||
|
||||
//输入部分
|
||||
pythonProcess.stdin.write(info.userId + '\n');
|
||||
pythonProcess.stdin.write(passwd + '\n');
|
||||
pythonProcess.stdin.write(year + '\n');
|
||||
pythonProcess.stdin.write(term + '\n');
|
||||
|
||||
//关闭
|
||||
pythonProcess.stdin.end();
|
||||
|
||||
let ret = '';
|
||||
|
||||
//获取输出
|
||||
pythonProcess.stdout.on('data', (data) => {
|
||||
ret += data.toString();
|
||||
});
|
||||
|
||||
//处理数据
|
||||
pythonProcess.on('close', (code) => {
|
||||
if (code === 0) {
|
||||
// Successfully executed the Python script
|
||||
// 'ret' now contains the output from the Python script
|
||||
console.log('Python script执行成功');
|
||||
console.log('输出结果:', ret);
|
||||
|
||||
// You can now send 'ret' as a response to your API request
|
||||
res.json({
|
||||
code: 1, // or another success code
|
||||
message: '获取课程成功',
|
||||
data: ret,
|
||||
});
|
||||
} else {
|
||||
// Error in executing the Python script
|
||||
res.json({
|
||||
code: 0,
|
||||
message: '获取课程失败',
|
||||
data: 'Python script执行失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: '获取课程失败',
|
||||
data: e,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = courseController;
|
||||
@ -0,0 +1,97 @@
|
||||
const task = require('../../model/xah/task');
|
||||
|
||||
const taskController = {
|
||||
|
||||
// 展示一个任务的详细内容
|
||||
showOnetask: async function(req,res,next){
|
||||
try{
|
||||
const id=req.body.id;
|
||||
console.log(id);
|
||||
let taskData = await task.selectOne(id);
|
||||
console.log(taskData);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "操作成功",
|
||||
data: taskData
|
||||
})
|
||||
}catch(e){
|
||||
res.json({ code: 0, message: "操作失败", data: e })
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
// 展示一个用户的所有任务
|
||||
showtask: async function(req,res,next){
|
||||
try{
|
||||
const id=req.body.userId;
|
||||
console.log(id);
|
||||
let taskData = await task.getTaskByUserId(id)
|
||||
//let taskData = await task.all()
|
||||
console.log(taskData);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "操作成功",
|
||||
data: taskData
|
||||
})
|
||||
}catch(e){
|
||||
res.json({ code: 0, message: "操作失败", data: e })
|
||||
}
|
||||
},
|
||||
// 新增一个任务
|
||||
addtask: async function(req, res, next) {
|
||||
try {
|
||||
const taskData = req.body; // 从请求中获取用户数据
|
||||
console.log(taskData);
|
||||
const result = await task.insert(taskData);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "任务添加成功",
|
||||
data: result
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "任务添加失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
//修改任务内容
|
||||
updatetask: async function(req, res, next) {
|
||||
try {
|
||||
const taskData = req.body; // 从请求中获取用户数据
|
||||
const result = await task.update(taskData.id,taskData);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "任务修改成功",
|
||||
data: taskData
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "任务修改失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
},
|
||||
//删除任务内容
|
||||
deletetask: async function(req, res, next) {
|
||||
try {
|
||||
const id = req.body.id; // 从请求中获取用户数据
|
||||
const result = await task.delete(id);
|
||||
res.json({
|
||||
code: 200,
|
||||
message: "任务删除成功",
|
||||
data: result
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({
|
||||
code: 0,
|
||||
message: "任务删除失败",
|
||||
data: e
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = taskController;
|
||||
@ -0,0 +1,50 @@
|
||||
const knex = require('../model/kenx');
|
||||
const jwt = require('jsonwebtoken');
|
||||
class Base{
|
||||
constructor(props){
|
||||
this.table = props;
|
||||
}
|
||||
|
||||
// 查找所有的信息
|
||||
all (){
|
||||
return knex(this.table).select();
|
||||
}
|
||||
|
||||
// 新增
|
||||
insert (params){
|
||||
return knex(this.table).insert(params);
|
||||
}
|
||||
|
||||
// 更改
|
||||
update (id, params){
|
||||
return knex(this.table).where('id', '=', id).update(params);
|
||||
}
|
||||
|
||||
// 删除
|
||||
delete (id){
|
||||
return knex(this.table).where('id', '=', id).del();
|
||||
}
|
||||
deleteAll (){
|
||||
return knex(this.table).del();
|
||||
}
|
||||
getById(field,id){
|
||||
console.log(field+id);
|
||||
return knex(this.table).select('*').where(field,'=',id);
|
||||
}
|
||||
generateAuthToken(){
|
||||
// 这里你可以使用jsonwebtoken或其他合适的库来生成令牌
|
||||
const token = jwt.sign({ /* 在令牌中包含的用户信息 */ }, 'ruanggong ', {
|
||||
expiresIn: '1h' // 令牌的过期时间
|
||||
});
|
||||
return token;
|
||||
}
|
||||
|
||||
|
||||
|
||||
selectOne(id){
|
||||
return knex(this.table).where('id','=',id).select();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Base;
|
||||
|
||||
@ -0,0 +1,20 @@
|
||||
// 引用配置文件
|
||||
const configs = require('../config');
|
||||
// 把配置文件中的信息,设置在初始化配置中
|
||||
module.exports = require('knex')({
|
||||
client: 'mysql',
|
||||
connection: {
|
||||
host: configs.mysql.host,
|
||||
port: configs.mysql.port,
|
||||
user: configs.mysql.user,
|
||||
password: configs.mysql.password,
|
||||
database: configs.mysql.database
|
||||
},
|
||||
// 打印错误
|
||||
log: {
|
||||
error (message) {
|
||||
console.log('[knex error]', message)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@ -0,0 +1,10 @@
|
||||
const Base = require('./base');
|
||||
|
||||
class Team extends Base {
|
||||
// 定义参数默认值为 team 表
|
||||
constructor(props = 'teams'){
|
||||
super(props);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Team();
|
||||
@ -0,0 +1,12 @@
|
||||
const Base = require('./base');
|
||||
|
||||
class User extends Base {
|
||||
// 定义参数默认值为 user 表
|
||||
constructor(props = 'users'){
|
||||
super(props);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
module.exports = new User();
|
||||
@ -0,0 +1,10 @@
|
||||
const Base = require('./base');
|
||||
|
||||
class Work extends Base {
|
||||
// 定义参数默认值为 team 表
|
||||
constructor(props = 'works'){
|
||||
super(props);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Work();
|
||||
@ -0,0 +1,18 @@
|
||||
const Base = require('../base');
|
||||
const knex=require('../kenx')
|
||||
|
||||
class Course extends Base {
|
||||
// 定义参数默认值为 user 表
|
||||
constructor(props = 'course'){
|
||||
super(props);
|
||||
}
|
||||
|
||||
//根据用户id查询用户所有的课程信息
|
||||
async getCourseByUserId(userId){
|
||||
return await knex.select('*').from('course').where('userId',userId)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
module.exports = new Course();
|
||||
@ -0,0 +1,15 @@
|
||||
const Base = require('../base');
|
||||
const knex=require('../kenx')
|
||||
|
||||
class Task extends Base {
|
||||
// 定义参数默认值为 user 表
|
||||
constructor(props = 'tasks'){
|
||||
super(props);
|
||||
}
|
||||
//根据用户id查询用户所有的课程信息
|
||||
async getTaskByUserId(userId){
|
||||
return await knex.select('*').from('tasks').where('userId',userId)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Task();
|
||||
@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../acorn/bin/acorn" "$@"
|
||||
else
|
||||
exec node "$basedir/../acorn/bin/acorn" "$@"
|
||||
fi
|
||||
@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\acorn\bin\acorn" %*
|
||||
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../clean-css/bin/cleancss" "$@"
|
||||
else
|
||||
exec node "$basedir/../clean-css/bin/cleancss" "$@"
|
||||
fi
|
||||
@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\clean-css\bin\cleancss" %*
|
||||
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../clean-css/bin/cleancss" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../clean-css/bin/cleancss" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../clean-css/bin/cleancss" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../clean-css/bin/cleancss" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../jade/bin/jade.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../jade/bin/jade.js" "$@"
|
||||
fi
|
||||
@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\jade\bin\jade.js" %*
|
||||
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../jade/bin/jade.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../jade/bin/jade.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../jade/bin/jade.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../jade/bin/jade.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../knex/bin/cli.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../knex/bin/cli.js" "$@"
|
||||
fi
|
||||
@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\knex\bin\cli.js" %*
|
||||
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../knex/bin/cli.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../knex/bin/cli.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../knex/bin/cli.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../knex/bin/cli.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../mime/cli.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../mime/cli.js" "$@"
|
||||
fi
|
||||
@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mime\cli.js" %*
|
||||
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../mime/cli.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../mime/cli.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../mime/cli.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../mime/cli.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../mkdirp/bin/cmd.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../mkdirp/bin/cmd.js" "$@"
|
||||
fi
|
||||
@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mkdirp\bin\cmd.js" %*
|
||||
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../resolve/bin/resolve" "$@"
|
||||
else
|
||||
exec node "$basedir/../resolve/bin/resolve" "$@"
|
||||
fi
|
||||
@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\resolve\bin\resolve" %*
|
||||
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../resolve/bin/resolve" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../resolve/bin/resolve" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../resolve/bin/resolve" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../resolve/bin/resolve" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../semver/bin/semver.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../semver/bin/semver.js" "$@"
|
||||
fi
|
||||
@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %*
|
||||
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../semver/bin/semver.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../uglify-js/bin/uglifyjs" "$@"
|
||||
else
|
||||
exec node "$basedir/../uglify-js/bin/uglifyjs" "$@"
|
||||
fi
|
||||
@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uglify-js\bin\uglifyjs" %*
|
||||
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../uglify-js/bin/uglifyjs" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../uglify-js/bin/uglifyjs" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../uglify-js/bin/uglifyjs" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../uglify-js/bin/uglifyjs" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,26 @@
|
||||
MIT License
|
||||
|
||||
Original Library
|
||||
- Copyright (c) Marak Squires
|
||||
|
||||
Additional Functionality
|
||||
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
|
||||
- Copyright (c) DABH (https://github.com/DABH)
|
||||
|
||||
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.
|
||||
@ -0,0 +1,219 @@
|
||||
# @colors/colors ("colors.js")
|
||||
[](https://github.com/DABH/colors.js/actions/workflows/ci.yml)
|
||||
[](https://www.npmjs.org/package/@colors/colors)
|
||||
|
||||
Please check out the [roadmap](ROADMAP.md) for upcoming features and releases. Please open Issues to provide feedback.
|
||||
|
||||
## get color and style in your node.js console
|
||||
|
||||

|
||||
|
||||
## Installation
|
||||
|
||||
npm install @colors/colors
|
||||
|
||||
## colors and styles!
|
||||
|
||||
### text colors
|
||||
|
||||
- black
|
||||
- red
|
||||
- green
|
||||
- yellow
|
||||
- blue
|
||||
- magenta
|
||||
- cyan
|
||||
- white
|
||||
- gray
|
||||
- grey
|
||||
|
||||
### bright text colors
|
||||
|
||||
- brightRed
|
||||
- brightGreen
|
||||
- brightYellow
|
||||
- brightBlue
|
||||
- brightMagenta
|
||||
- brightCyan
|
||||
- brightWhite
|
||||
|
||||
### background colors
|
||||
|
||||
- bgBlack
|
||||
- bgRed
|
||||
- bgGreen
|
||||
- bgYellow
|
||||
- bgBlue
|
||||
- bgMagenta
|
||||
- bgCyan
|
||||
- bgWhite
|
||||
- bgGray
|
||||
- bgGrey
|
||||
|
||||
### bright background colors
|
||||
|
||||
- bgBrightRed
|
||||
- bgBrightGreen
|
||||
- bgBrightYellow
|
||||
- bgBrightBlue
|
||||
- bgBrightMagenta
|
||||
- bgBrightCyan
|
||||
- bgBrightWhite
|
||||
|
||||
### styles
|
||||
|
||||
- reset
|
||||
- bold
|
||||
- dim
|
||||
- italic
|
||||
- underline
|
||||
- inverse
|
||||
- hidden
|
||||
- strikethrough
|
||||
|
||||
### extras
|
||||
|
||||
- rainbow
|
||||
- zebra
|
||||
- america
|
||||
- trap
|
||||
- random
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
By popular demand, `@colors/colors` now ships with two types of usages!
|
||||
|
||||
The super nifty way
|
||||
|
||||
```js
|
||||
var colors = require('@colors/colors');
|
||||
|
||||
console.log('hello'.green); // outputs green text
|
||||
console.log('i like cake and pies'.underline.red); // outputs red underlined text
|
||||
console.log('inverse the color'.inverse); // inverses the color
|
||||
console.log('OMG Rainbows!'.rainbow); // rainbow
|
||||
console.log('Run the trap'.trap); // Drops the bass
|
||||
|
||||
```
|
||||
|
||||
or a slightly less nifty way which doesn't extend `String.prototype`
|
||||
|
||||
```js
|
||||
var colors = require('@colors/colors/safe');
|
||||
|
||||
console.log(colors.green('hello')); // outputs green text
|
||||
console.log(colors.red.underline('i like cake and pies')); // outputs red underlined text
|
||||
console.log(colors.inverse('inverse the color')); // inverses the color
|
||||
console.log(colors.rainbow('OMG Rainbows!')); // rainbow
|
||||
console.log(colors.trap('Run the trap')); // Drops the bass
|
||||
|
||||
```
|
||||
|
||||
I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way.
|
||||
|
||||
If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object.
|
||||
|
||||
## Enabling/Disabling Colors
|
||||
|
||||
The package will auto-detect whether your terminal can use colors and enable/disable accordingly. When colors are disabled, the color functions do nothing. You can override this with a command-line flag:
|
||||
|
||||
```bash
|
||||
node myapp.js --no-color
|
||||
node myapp.js --color=false
|
||||
|
||||
node myapp.js --color
|
||||
node myapp.js --color=true
|
||||
node myapp.js --color=always
|
||||
|
||||
FORCE_COLOR=1 node myapp.js
|
||||
```
|
||||
|
||||
Or in code:
|
||||
|
||||
```javascript
|
||||
var colors = require('@colors/colors');
|
||||
colors.enable();
|
||||
colors.disable();
|
||||
```
|
||||
|
||||
## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data)
|
||||
|
||||
```js
|
||||
var name = 'Beowulf';
|
||||
console.log(colors.green('Hello %s'), name);
|
||||
// outputs -> 'Hello Beowulf'
|
||||
```
|
||||
|
||||
## Custom themes
|
||||
|
||||
### Using standard API
|
||||
|
||||
```js
|
||||
|
||||
var colors = require('@colors/colors');
|
||||
|
||||
colors.setTheme({
|
||||
silly: 'rainbow',
|
||||
input: 'grey',
|
||||
verbose: 'cyan',
|
||||
prompt: 'grey',
|
||||
info: 'green',
|
||||
data: 'grey',
|
||||
help: 'cyan',
|
||||
warn: 'yellow',
|
||||
debug: 'blue',
|
||||
error: 'red'
|
||||
});
|
||||
|
||||
// outputs red text
|
||||
console.log("this is an error".error);
|
||||
|
||||
// outputs yellow text
|
||||
console.log("this is a warning".warn);
|
||||
```
|
||||
|
||||
### Using string safe API
|
||||
|
||||
```js
|
||||
var colors = require('@colors/colors/safe');
|
||||
|
||||
// set single property
|
||||
var error = colors.red;
|
||||
error('this is red');
|
||||
|
||||
// set theme
|
||||
colors.setTheme({
|
||||
silly: 'rainbow',
|
||||
input: 'grey',
|
||||
verbose: 'cyan',
|
||||
prompt: 'grey',
|
||||
info: 'green',
|
||||
data: 'grey',
|
||||
help: 'cyan',
|
||||
warn: 'yellow',
|
||||
debug: 'blue',
|
||||
error: 'red'
|
||||
});
|
||||
|
||||
// outputs red text
|
||||
console.log(colors.error("this is an error"));
|
||||
|
||||
// outputs yellow text
|
||||
console.log(colors.warn("this is a warning"));
|
||||
|
||||
```
|
||||
|
||||
### Combining Colors
|
||||
|
||||
```javascript
|
||||
var colors = require('@colors/colors');
|
||||
|
||||
colors.setTheme({
|
||||
custom: ['red', 'underline']
|
||||
});
|
||||
|
||||
console.log('test'.custom);
|
||||
```
|
||||
|
||||
*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.*
|
||||
@ -0,0 +1,83 @@
|
||||
var colors = require('../lib/index');
|
||||
|
||||
console.log('First some yellow text'.yellow);
|
||||
|
||||
console.log('Underline that text'.yellow.underline);
|
||||
|
||||
console.log('Make it bold and red'.red.bold);
|
||||
|
||||
console.log(('Double Raindows All Day Long').rainbow);
|
||||
|
||||
console.log('Drop the bass'.trap);
|
||||
|
||||
console.log('DROP THE RAINBOW BASS'.trap.rainbow);
|
||||
|
||||
// styles not widely supported
|
||||
console.log('Chains are also cool.'.bold.italic.underline.red);
|
||||
|
||||
// styles not widely supported
|
||||
console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse
|
||||
+ ' styles! '.yellow.bold);
|
||||
console.log('Zebras are so fun!'.zebra);
|
||||
|
||||
//
|
||||
// Remark: .strikethrough may not work with Mac OS Terminal App
|
||||
//
|
||||
console.log('This is ' + 'not'.strikethrough + ' fun.');
|
||||
|
||||
console.log('Background color attack!'.black.bgWhite);
|
||||
console.log('Use random styles on everything!'.random);
|
||||
console.log('America, Heck Yeah!'.america);
|
||||
|
||||
// eslint-disable-next-line max-len
|
||||
console.log('Blindingly '.brightCyan + 'bright? '.brightRed + 'Why '.brightYellow + 'not?!'.brightGreen);
|
||||
|
||||
console.log('Setting themes is useful');
|
||||
|
||||
//
|
||||
// Custom themes
|
||||
//
|
||||
console.log('Generic logging theme as JSON'.green.bold.underline);
|
||||
// Load theme with JSON literal
|
||||
colors.setTheme({
|
||||
silly: 'rainbow',
|
||||
input: 'grey',
|
||||
verbose: 'cyan',
|
||||
prompt: 'grey',
|
||||
info: 'green',
|
||||
data: 'grey',
|
||||
help: 'cyan',
|
||||
warn: 'yellow',
|
||||
debug: 'blue',
|
||||
error: 'red',
|
||||
});
|
||||
|
||||
// outputs red text
|
||||
console.log('this is an error'.error);
|
||||
|
||||
// outputs yellow text
|
||||
console.log('this is a warning'.warn);
|
||||
|
||||
// outputs grey text
|
||||
console.log('this is an input'.input);
|
||||
|
||||
console.log('Generic logging theme as file'.green.bold.underline);
|
||||
|
||||
// Load a theme from file
|
||||
try {
|
||||
colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
|
||||
// outputs red text
|
||||
console.log('this is an error'.error);
|
||||
|
||||
// outputs yellow text
|
||||
console.log('this is a warning'.warn);
|
||||
|
||||
// outputs grey text
|
||||
console.log('this is an input'.input);
|
||||
|
||||
// console.log("Don't summon".zalgo)
|
||||
|
||||
@ -0,0 +1,80 @@
|
||||
var colors = require('../safe');
|
||||
|
||||
console.log(colors.yellow('First some yellow text'));
|
||||
|
||||
console.log(colors.yellow.underline('Underline that text'));
|
||||
|
||||
console.log(colors.red.bold('Make it bold and red'));
|
||||
|
||||
console.log(colors.rainbow('Double Raindows All Day Long'));
|
||||
|
||||
console.log(colors.trap('Drop the bass'));
|
||||
|
||||
console.log(colors.rainbow(colors.trap('DROP THE RAINBOW BASS')));
|
||||
|
||||
// styles not widely supported
|
||||
console.log(colors.bold.italic.underline.red('Chains are also cool.'));
|
||||
|
||||
// styles not widely supported
|
||||
console.log(colors.green('So ') + colors.underline('are') + ' '
|
||||
+ colors.inverse('inverse') + colors.yellow.bold(' styles! '));
|
||||
|
||||
console.log(colors.zebra('Zebras are so fun!'));
|
||||
|
||||
console.log('This is ' + colors.strikethrough('not') + ' fun.');
|
||||
|
||||
|
||||
console.log(colors.black.bgWhite('Background color attack!'));
|
||||
console.log(colors.random('Use random styles on everything!'));
|
||||
console.log(colors.america('America, Heck Yeah!'));
|
||||
|
||||
// eslint-disable-next-line max-len
|
||||
console.log(colors.brightCyan('Blindingly ') + colors.brightRed('bright? ') + colors.brightYellow('Why ') + colors.brightGreen('not?!'));
|
||||
|
||||
console.log('Setting themes is useful');
|
||||
|
||||
//
|
||||
// Custom themes
|
||||
//
|
||||
// console.log('Generic logging theme as JSON'.green.bold.underline);
|
||||
// Load theme with JSON literal
|
||||
colors.setTheme({
|
||||
silly: 'rainbow',
|
||||
input: 'blue',
|
||||
verbose: 'cyan',
|
||||
prompt: 'grey',
|
||||
info: 'green',
|
||||
data: 'grey',
|
||||
help: 'cyan',
|
||||
warn: 'yellow',
|
||||
debug: 'blue',
|
||||
error: 'red',
|
||||
});
|
||||
|
||||
// outputs red text
|
||||
console.log(colors.error('this is an error'));
|
||||
|
||||
// outputs yellow text
|
||||
console.log(colors.warn('this is a warning'));
|
||||
|
||||
// outputs blue text
|
||||
console.log(colors.input('this is an input'));
|
||||
|
||||
|
||||
// console.log('Generic logging theme as file'.green.bold.underline);
|
||||
|
||||
// Load a theme from file
|
||||
colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));
|
||||
|
||||
// outputs red text
|
||||
console.log(colors.error('this is an error'));
|
||||
|
||||
// outputs yellow text
|
||||
console.log(colors.warn('this is a warning'));
|
||||
|
||||
// outputs grey text
|
||||
console.log(colors.input('this is an input'));
|
||||
|
||||
// console.log(colors.zalgo("Don't summon him"))
|
||||
|
||||
|
||||
@ -0,0 +1,184 @@
|
||||
// Type definitions for @colors/colors 1.4+
|
||||
// Project: https://github.com/Marak/colors.js
|
||||
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Staffan Eketorp <https://github.com/staeke>
|
||||
// Definitions: https://github.com/DABH/colors.js
|
||||
|
||||
export interface Color {
|
||||
(text: string): string;
|
||||
|
||||
strip: Color;
|
||||
stripColors: Color;
|
||||
|
||||
black: Color;
|
||||
red: Color;
|
||||
green: Color;
|
||||
yellow: Color;
|
||||
blue: Color;
|
||||
magenta: Color;
|
||||
cyan: Color;
|
||||
white: Color;
|
||||
gray: Color;
|
||||
grey: Color;
|
||||
|
||||
brightRed: Color;
|
||||
brightGreen: Color;
|
||||
brightYellow: Color;
|
||||
brightBlue: Color;
|
||||
brightMagenta: Color;
|
||||
brightCyan: Color;
|
||||
brightWhite: Color;
|
||||
|
||||
bgBlack: Color;
|
||||
bgRed: Color;
|
||||
bgGreen: Color;
|
||||
bgYellow: Color;
|
||||
bgBlue: Color;
|
||||
bgMagenta: Color;
|
||||
bgCyan: Color;
|
||||
bgWhite: Color;
|
||||
|
||||
bgBrightRed: Color;
|
||||
bgBrightGreen: Color;
|
||||
bgBrightYellow: Color;
|
||||
bgBrightBlue: Color;
|
||||
bgBrightMagenta: Color;
|
||||
bgBrightCyan: Color;
|
||||
bgBrightWhite: Color;
|
||||
|
||||
reset: Color;
|
||||
bold: Color;
|
||||
dim: Color;
|
||||
italic: Color;
|
||||
underline: Color;
|
||||
inverse: Color;
|
||||
hidden: Color;
|
||||
strikethrough: Color;
|
||||
|
||||
rainbow: Color;
|
||||
zebra: Color;
|
||||
america: Color;
|
||||
trap: Color;
|
||||
random: Color;
|
||||
zalgo: Color;
|
||||
}
|
||||
|
||||
export function enable(): void;
|
||||
export function disable(): void;
|
||||
export function setTheme(theme: any): void;
|
||||
|
||||
export let enabled: boolean;
|
||||
|
||||
export const strip: Color;
|
||||
export const stripColors: Color;
|
||||
|
||||
export const black: Color;
|
||||
export const red: Color;
|
||||
export const green: Color;
|
||||
export const yellow: Color;
|
||||
export const blue: Color;
|
||||
export const magenta: Color;
|
||||
export const cyan: Color;
|
||||
export const white: Color;
|
||||
export const gray: Color;
|
||||
export const grey: Color;
|
||||
|
||||
export const brightRed: Color;
|
||||
export const brightGreen: Color;
|
||||
export const brightYellow: Color;
|
||||
export const brightBlue: Color;
|
||||
export const brightMagenta: Color;
|
||||
export const brightCyan: Color;
|
||||
export const brightWhite: Color;
|
||||
|
||||
export const bgBlack: Color;
|
||||
export const bgRed: Color;
|
||||
export const bgGreen: Color;
|
||||
export const bgYellow: Color;
|
||||
export const bgBlue: Color;
|
||||
export const bgMagenta: Color;
|
||||
export const bgCyan: Color;
|
||||
export const bgWhite: Color;
|
||||
|
||||
export const bgBrightRed: Color;
|
||||
export const bgBrightGreen: Color;
|
||||
export const bgBrightYellow: Color;
|
||||
export const bgBrightBlue: Color;
|
||||
export const bgBrightMagenta: Color;
|
||||
export const bgBrightCyan: Color;
|
||||
export const bgBrightWhite: Color;
|
||||
|
||||
export const reset: Color;
|
||||
export const bold: Color;
|
||||
export const dim: Color;
|
||||
export const italic: Color;
|
||||
export const underline: Color;
|
||||
export const inverse: Color;
|
||||
export const hidden: Color;
|
||||
export const strikethrough: Color;
|
||||
|
||||
export const rainbow: Color;
|
||||
export const zebra: Color;
|
||||
export const america: Color;
|
||||
export const trap: Color;
|
||||
export const random: Color;
|
||||
export const zalgo: Color;
|
||||
|
||||
declare global {
|
||||
interface String {
|
||||
strip: string;
|
||||
stripColors: string;
|
||||
|
||||
black: string;
|
||||
red: string;
|
||||
green: string;
|
||||
yellow: string;
|
||||
blue: string;
|
||||
magenta: string;
|
||||
cyan: string;
|
||||
white: string;
|
||||
gray: string;
|
||||
grey: string;
|
||||
|
||||
brightRed: string;
|
||||
brightGreen: string;
|
||||
brightYellow: string;
|
||||
brightBlue: string;
|
||||
brightMagenta: string;
|
||||
brightCyan: string;
|
||||
brightWhite: string;
|
||||
|
||||
bgBlack: string;
|
||||
bgRed: string;
|
||||
bgGreen: string;
|
||||
bgYellow: string;
|
||||
bgBlue: string;
|
||||
bgMagenta: string;
|
||||
bgCyan: string;
|
||||
bgWhite: string;
|
||||
|
||||
bgBrightRed: string;
|
||||
bgBrightGreen: string;
|
||||
bgBrightYellow: string;
|
||||
bgBrightBlue: string;
|
||||
bgBrightMagenta: string;
|
||||
bgBrightCyan: string;
|
||||
bgBrightWhite: string;
|
||||
|
||||
reset: string;
|
||||
// @ts-ignore
|
||||
bold: string;
|
||||
dim: string;
|
||||
italic: string;
|
||||
underline: string;
|
||||
inverse: string;
|
||||
hidden: string;
|
||||
strikethrough: string;
|
||||
|
||||
rainbow: string;
|
||||
zebra: string;
|
||||
america: string;
|
||||
trap: string;
|
||||
random: string;
|
||||
zalgo: string;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,211 @@
|
||||
/*
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Original Library
|
||||
- Copyright (c) Marak Squires
|
||||
|
||||
Additional functionality
|
||||
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
var colors = {};
|
||||
module['exports'] = colors;
|
||||
|
||||
colors.themes = {};
|
||||
|
||||
var util = require('util');
|
||||
var ansiStyles = colors.styles = require('./styles');
|
||||
var defineProps = Object.defineProperties;
|
||||
var newLineRegex = new RegExp(/[\r\n]+/g);
|
||||
|
||||
colors.supportsColor = require('./system/supports-colors').supportsColor;
|
||||
|
||||
if (typeof colors.enabled === 'undefined') {
|
||||
colors.enabled = colors.supportsColor() !== false;
|
||||
}
|
||||
|
||||
colors.enable = function() {
|
||||
colors.enabled = true;
|
||||
};
|
||||
|
||||
colors.disable = function() {
|
||||
colors.enabled = false;
|
||||
};
|
||||
|
||||
colors.stripColors = colors.strip = function(str) {
|
||||
return ('' + str).replace(/\x1B\[\d+m/g, '');
|
||||
};
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
var stylize = colors.stylize = function stylize(str, style) {
|
||||
if (!colors.enabled) {
|
||||
return str+'';
|
||||
}
|
||||
|
||||
var styleMap = ansiStyles[style];
|
||||
|
||||
// Stylize should work for non-ANSI styles, too
|
||||
if (!styleMap && style in colors) {
|
||||
// Style maps like trap operate as functions on strings;
|
||||
// they don't have properties like open or close.
|
||||
return colors[style](str);
|
||||
}
|
||||
|
||||
return styleMap.open + str + styleMap.close;
|
||||
};
|
||||
|
||||
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
|
||||
var escapeStringRegexp = function(str) {
|
||||
if (typeof str !== 'string') {
|
||||
throw new TypeError('Expected a string');
|
||||
}
|
||||
return str.replace(matchOperatorsRe, '\\$&');
|
||||
};
|
||||
|
||||
function build(_styles) {
|
||||
var builder = function builder() {
|
||||
return applyStyle.apply(builder, arguments);
|
||||
};
|
||||
builder._styles = _styles;
|
||||
// __proto__ is used because we must return a function, but there is
|
||||
// no way to create a function with a different prototype.
|
||||
builder.__proto__ = proto;
|
||||
return builder;
|
||||
}
|
||||
|
||||
var styles = (function() {
|
||||
var ret = {};
|
||||
ansiStyles.grey = ansiStyles.gray;
|
||||
Object.keys(ansiStyles).forEach(function(key) {
|
||||
ansiStyles[key].closeRe =
|
||||
new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
|
||||
ret[key] = {
|
||||
get: function() {
|
||||
return build(this._styles.concat(key));
|
||||
},
|
||||
};
|
||||
});
|
||||
return ret;
|
||||
})();
|
||||
|
||||
var proto = defineProps(function colors() {}, styles);
|
||||
|
||||
function applyStyle() {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
|
||||
var str = args.map(function(arg) {
|
||||
// Use weak equality check so we can colorize null/undefined in safe mode
|
||||
if (arg != null && arg.constructor === String) {
|
||||
return arg;
|
||||
} else {
|
||||
return util.inspect(arg);
|
||||
}
|
||||
}).join(' ');
|
||||
|
||||
if (!colors.enabled || !str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
var newLinesPresent = str.indexOf('\n') != -1;
|
||||
|
||||
var nestedStyles = this._styles;
|
||||
|
||||
var i = nestedStyles.length;
|
||||
while (i--) {
|
||||
var code = ansiStyles[nestedStyles[i]];
|
||||
str = code.open + str.replace(code.closeRe, code.open) + code.close;
|
||||
if (newLinesPresent) {
|
||||
str = str.replace(newLineRegex, function(match) {
|
||||
return code.close + match + code.open;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
colors.setTheme = function(theme) {
|
||||
if (typeof theme === 'string') {
|
||||
console.log('colors.setTheme now only accepts an object, not a string. ' +
|
||||
'If you are trying to set a theme from a file, it is now your (the ' +
|
||||
'caller\'s) responsibility to require the file. The old syntax ' +
|
||||
'looked like colors.setTheme(__dirname + ' +
|
||||
'\'/../themes/generic-logging.js\'); The new syntax looks like '+
|
||||
'colors.setTheme(require(__dirname + ' +
|
||||
'\'/../themes/generic-logging.js\'));');
|
||||
return;
|
||||
}
|
||||
for (var style in theme) {
|
||||
(function(style) {
|
||||
colors[style] = function(str) {
|
||||
if (typeof theme[style] === 'object') {
|
||||
var out = str;
|
||||
for (var i in theme[style]) {
|
||||
out = colors[theme[style][i]](out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return colors[theme[style]](str);
|
||||
};
|
||||
})(style);
|
||||
}
|
||||
};
|
||||
|
||||
function init() {
|
||||
var ret = {};
|
||||
Object.keys(styles).forEach(function(name) {
|
||||
ret[name] = {
|
||||
get: function() {
|
||||
return build([name]);
|
||||
},
|
||||
};
|
||||
});
|
||||
return ret;
|
||||
}
|
||||
|
||||
var sequencer = function sequencer(map, str) {
|
||||
var exploded = str.split('');
|
||||
exploded = exploded.map(map);
|
||||
return exploded.join('');
|
||||
};
|
||||
|
||||
// custom formatter methods
|
||||
colors.trap = require('./custom/trap');
|
||||
colors.zalgo = require('./custom/zalgo');
|
||||
|
||||
// maps
|
||||
colors.maps = {};
|
||||
colors.maps.america = require('./maps/america')(colors);
|
||||
colors.maps.zebra = require('./maps/zebra')(colors);
|
||||
colors.maps.rainbow = require('./maps/rainbow')(colors);
|
||||
colors.maps.random = require('./maps/random')(colors);
|
||||
|
||||
for (var map in colors.maps) {
|
||||
(function(map) {
|
||||
colors[map] = function(str) {
|
||||
return sequencer(colors.maps[map], str);
|
||||
};
|
||||
})(map);
|
||||
}
|
||||
|
||||
defineProps(colors, init());
|
||||
@ -0,0 +1,46 @@
|
||||
module['exports'] = function runTheTrap(text, options) {
|
||||
var result = '';
|
||||
text = text || 'Run the trap, drop the bass';
|
||||
text = text.split('');
|
||||
var trap = {
|
||||
a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'],
|
||||
b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'],
|
||||
c: ['\u00a9', '\u023b', '\u03fe'],
|
||||
d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'],
|
||||
e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc',
|
||||
'\u0a6c'],
|
||||
f: ['\u04fa'],
|
||||
g: ['\u0262'],
|
||||
h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'],
|
||||
i: ['\u0f0f'],
|
||||
j: ['\u0134'],
|
||||
k: ['\u0138', '\u04a0', '\u04c3', '\u051e'],
|
||||
l: ['\u0139'],
|
||||
m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'],
|
||||
n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'],
|
||||
o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd',
|
||||
'\u06dd', '\u0e4f'],
|
||||
p: ['\u01f7', '\u048e'],
|
||||
q: ['\u09cd'],
|
||||
r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'],
|
||||
s: ['\u00a7', '\u03de', '\u03df', '\u03e8'],
|
||||
t: ['\u0141', '\u0166', '\u0373'],
|
||||
u: ['\u01b1', '\u054d'],
|
||||
v: ['\u05d8'],
|
||||
w: ['\u0428', '\u0460', '\u047c', '\u0d70'],
|
||||
x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'],
|
||||
y: ['\u00a5', '\u04b0', '\u04cb'],
|
||||
z: ['\u01b5', '\u0240'],
|
||||
};
|
||||
text.forEach(function(c) {
|
||||
c = c.toLowerCase();
|
||||
var chars = trap[c] || [' '];
|
||||
var rand = Math.floor(Math.random() * chars.length);
|
||||
if (typeof trap[c] !== 'undefined') {
|
||||
result += trap[c][rand];
|
||||
} else {
|
||||
result += c;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
};
|
||||
@ -0,0 +1,110 @@
|
||||
// please no
|
||||
module['exports'] = function zalgo(text, options) {
|
||||
text = text || ' he is here ';
|
||||
var soul = {
|
||||
'up': [
|
||||
'̍', '̎', '̄', '̅',
|
||||
'̿', '̑', '̆', '̐',
|
||||
'͒', '͗', '͑', '̇',
|
||||
'̈', '̊', '͂', '̓',
|
||||
'̈', '͊', '͋', '͌',
|
||||
'̃', '̂', '̌', '͐',
|
||||
'̀', '́', '̋', '̏',
|
||||
'̒', '̓', '̔', '̽',
|
||||
'̉', 'ͣ', 'ͤ', 'ͥ',
|
||||
'ͦ', 'ͧ', 'ͨ', 'ͩ',
|
||||
'ͪ', 'ͫ', 'ͬ', 'ͭ',
|
||||
'ͮ', 'ͯ', '̾', '͛',
|
||||
'͆', '̚',
|
||||
],
|
||||
'down': [
|
||||
'̖', '̗', '̘', '̙',
|
||||
'̜', '̝', '̞', '̟',
|
||||
'̠', '̤', '̥', '̦',
|
||||
'̩', '̪', '̫', '̬',
|
||||
'̭', '̮', '̯', '̰',
|
||||
'̱', '̲', '̳', '̹',
|
||||
'̺', '̻', '̼', 'ͅ',
|
||||
'͇', '͈', '͉', '͍',
|
||||
'͎', '͓', '͔', '͕',
|
||||
'͖', '͙', '͚', '̣',
|
||||
],
|
||||
'mid': [
|
||||
'̕', '̛', '̀', '́',
|
||||
'͘', '̡', '̢', '̧',
|
||||
'̨', '̴', '̵', '̶',
|
||||
'͜', '͝', '͞',
|
||||
'͟', '͠', '͢', '̸',
|
||||
'̷', '͡', ' ҉',
|
||||
],
|
||||
};
|
||||
var all = [].concat(soul.up, soul.down, soul.mid);
|
||||
|
||||
function randomNumber(range) {
|
||||
var r = Math.floor(Math.random() * range);
|
||||
return r;
|
||||
}
|
||||
|
||||
function isChar(character) {
|
||||
var bool = false;
|
||||
all.filter(function(i) {
|
||||
bool = (i === character);
|
||||
});
|
||||
return bool;
|
||||
}
|
||||
|
||||
|
||||
function heComes(text, options) {
|
||||
var result = '';
|
||||
var counts;
|
||||
var l;
|
||||
options = options || {};
|
||||
options['up'] =
|
||||
typeof options['up'] !== 'undefined' ? options['up'] : true;
|
||||
options['mid'] =
|
||||
typeof options['mid'] !== 'undefined' ? options['mid'] : true;
|
||||
options['down'] =
|
||||
typeof options['down'] !== 'undefined' ? options['down'] : true;
|
||||
options['size'] =
|
||||
typeof options['size'] !== 'undefined' ? options['size'] : 'maxi';
|
||||
text = text.split('');
|
||||
for (l in text) {
|
||||
if (isChar(l)) {
|
||||
continue;
|
||||
}
|
||||
result = result + text[l];
|
||||
counts = {'up': 0, 'down': 0, 'mid': 0};
|
||||
switch (options.size) {
|
||||
case 'mini':
|
||||
counts.up = randomNumber(8);
|
||||
counts.mid = randomNumber(2);
|
||||
counts.down = randomNumber(8);
|
||||
break;
|
||||
case 'maxi':
|
||||
counts.up = randomNumber(16) + 3;
|
||||
counts.mid = randomNumber(4) + 1;
|
||||
counts.down = randomNumber(64) + 3;
|
||||
break;
|
||||
default:
|
||||
counts.up = randomNumber(8) + 1;
|
||||
counts.mid = randomNumber(6) / 2;
|
||||
counts.down = randomNumber(8) + 1;
|
||||
break;
|
||||
}
|
||||
|
||||
var arr = ['up', 'mid', 'down'];
|
||||
for (var d in arr) {
|
||||
var index = arr[d];
|
||||
for (var i = 0; i <= counts[index]; i++) {
|
||||
if (options[index]) {
|
||||
result = result + soul[index][randomNumber(soul[index].length)];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// don't summon him
|
||||
return heComes(text, options);
|
||||
};
|
||||
|
||||
@ -0,0 +1,110 @@
|
||||
var colors = require('./colors');
|
||||
|
||||
module['exports'] = function() {
|
||||
//
|
||||
// Extends prototype of native string object to allow for "foo".red syntax
|
||||
//
|
||||
var addProperty = function(color, func) {
|
||||
String.prototype.__defineGetter__(color, func);
|
||||
};
|
||||
|
||||
addProperty('strip', function() {
|
||||
return colors.strip(this);
|
||||
});
|
||||
|
||||
addProperty('stripColors', function() {
|
||||
return colors.strip(this);
|
||||
});
|
||||
|
||||
addProperty('trap', function() {
|
||||
return colors.trap(this);
|
||||
});
|
||||
|
||||
addProperty('zalgo', function() {
|
||||
return colors.zalgo(this);
|
||||
});
|
||||
|
||||
addProperty('zebra', function() {
|
||||
return colors.zebra(this);
|
||||
});
|
||||
|
||||
addProperty('rainbow', function() {
|
||||
return colors.rainbow(this);
|
||||
});
|
||||
|
||||
addProperty('random', function() {
|
||||
return colors.random(this);
|
||||
});
|
||||
|
||||
addProperty('america', function() {
|
||||
return colors.america(this);
|
||||
});
|
||||
|
||||
//
|
||||
// Iterate through all default styles and colors
|
||||
//
|
||||
var x = Object.keys(colors.styles);
|
||||
x.forEach(function(style) {
|
||||
addProperty(style, function() {
|
||||
return colors.stylize(this, style);
|
||||
});
|
||||
});
|
||||
|
||||
function applyTheme(theme) {
|
||||
//
|
||||
// Remark: This is a list of methods that exist
|
||||
// on String that you should not overwrite.
|
||||
//
|
||||
var stringPrototypeBlacklist = [
|
||||
'__defineGetter__', '__defineSetter__', '__lookupGetter__',
|
||||
'__lookupSetter__', 'charAt', 'constructor', 'hasOwnProperty',
|
||||
'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString',
|
||||
'valueOf', 'charCodeAt', 'indexOf', 'lastIndexOf', 'length',
|
||||
'localeCompare', 'match', 'repeat', 'replace', 'search', 'slice',
|
||||
'split', 'substring', 'toLocaleLowerCase', 'toLocaleUpperCase',
|
||||
'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight',
|
||||
];
|
||||
|
||||
Object.keys(theme).forEach(function(prop) {
|
||||
if (stringPrototypeBlacklist.indexOf(prop) !== -1) {
|
||||
console.log('warn: '.red + ('String.prototype' + prop).magenta +
|
||||
' is probably something you don\'t want to override. ' +
|
||||
'Ignoring style name');
|
||||
} else {
|
||||
if (typeof(theme[prop]) === 'string') {
|
||||
colors[prop] = colors[theme[prop]];
|
||||
addProperty(prop, function() {
|
||||
return colors[prop](this);
|
||||
});
|
||||
} else {
|
||||
var themePropApplicator = function(str) {
|
||||
var ret = str || this;
|
||||
for (var t = 0; t < theme[prop].length; t++) {
|
||||
ret = colors[theme[prop][t]](ret);
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
addProperty(prop, themePropApplicator);
|
||||
colors[prop] = function(str) {
|
||||
return themePropApplicator(str);
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
colors.setTheme = function(theme) {
|
||||
if (typeof theme === 'string') {
|
||||
console.log('colors.setTheme now only accepts an object, not a string. ' +
|
||||
'If you are trying to set a theme from a file, it is now your (the ' +
|
||||
'caller\'s) responsibility to require the file. The old syntax ' +
|
||||
'looked like colors.setTheme(__dirname + ' +
|
||||
'\'/../themes/generic-logging.js\'); The new syntax looks like '+
|
||||
'colors.setTheme(require(__dirname + ' +
|
||||
'\'/../themes/generic-logging.js\'));');
|
||||
return;
|
||||
} else {
|
||||
applyTheme(theme);
|
||||
}
|
||||
};
|
||||
};
|
||||
@ -0,0 +1,13 @@
|
||||
var colors = require('./colors');
|
||||
module['exports'] = colors;
|
||||
|
||||
// Remark: By default, colors will add style properties to String.prototype.
|
||||
//
|
||||
// If you don't wish to extend String.prototype, you can do this instead and
|
||||
// native String will not be touched:
|
||||
//
|
||||
// var colors = require('@colors/colors/safe');
|
||||
// colors.red("foo")
|
||||
//
|
||||
//
|
||||
require('./extendStringPrototype')();
|
||||
@ -0,0 +1,10 @@
|
||||
module['exports'] = function(colors) {
|
||||
return function(letter, i, exploded) {
|
||||
if (letter === ' ') return letter;
|
||||
switch (i%3) {
|
||||
case 0: return colors.red(letter);
|
||||
case 1: return colors.white(letter);
|
||||
case 2: return colors.blue(letter);
|
||||
}
|
||||
};
|
||||
};
|
||||
@ -0,0 +1,12 @@
|
||||
module['exports'] = function(colors) {
|
||||
// RoY G BiV
|
||||
var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta'];
|
||||
return function(letter, i, exploded) {
|
||||
if (letter === ' ') {
|
||||
return letter;
|
||||
} else {
|
||||
return colors[rainbowColors[i++ % rainbowColors.length]](letter);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@ -0,0 +1,11 @@
|
||||
module['exports'] = function(colors) {
|
||||
var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green',
|
||||
'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed',
|
||||
'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta'];
|
||||
return function(letter, i, exploded) {
|
||||
return letter === ' ' ? letter :
|
||||
colors[
|
||||
available[Math.round(Math.random() * (available.length - 2))]
|
||||
](letter);
|
||||
};
|
||||
};
|
||||
@ -0,0 +1,5 @@
|
||||
module['exports'] = function(colors) {
|
||||
return function(letter, i, exploded) {
|
||||
return i % 2 === 0 ? letter : colors.inverse(letter);
|
||||
};
|
||||
};
|
||||
@ -0,0 +1,95 @@
|
||||
/*
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
var styles = {};
|
||||
module['exports'] = styles;
|
||||
|
||||
var codes = {
|
||||
reset: [0, 0],
|
||||
|
||||
bold: [1, 22],
|
||||
dim: [2, 22],
|
||||
italic: [3, 23],
|
||||
underline: [4, 24],
|
||||
inverse: [7, 27],
|
||||
hidden: [8, 28],
|
||||
strikethrough: [9, 29],
|
||||
|
||||
black: [30, 39],
|
||||
red: [31, 39],
|
||||
green: [32, 39],
|
||||
yellow: [33, 39],
|
||||
blue: [34, 39],
|
||||
magenta: [35, 39],
|
||||
cyan: [36, 39],
|
||||
white: [37, 39],
|
||||
gray: [90, 39],
|
||||
grey: [90, 39],
|
||||
|
||||
brightRed: [91, 39],
|
||||
brightGreen: [92, 39],
|
||||
brightYellow: [93, 39],
|
||||
brightBlue: [94, 39],
|
||||
brightMagenta: [95, 39],
|
||||
brightCyan: [96, 39],
|
||||
brightWhite: [97, 39],
|
||||
|
||||
bgBlack: [40, 49],
|
||||
bgRed: [41, 49],
|
||||
bgGreen: [42, 49],
|
||||
bgYellow: [43, 49],
|
||||
bgBlue: [44, 49],
|
||||
bgMagenta: [45, 49],
|
||||
bgCyan: [46, 49],
|
||||
bgWhite: [47, 49],
|
||||
bgGray: [100, 49],
|
||||
bgGrey: [100, 49],
|
||||
|
||||
bgBrightRed: [101, 49],
|
||||
bgBrightGreen: [102, 49],
|
||||
bgBrightYellow: [103, 49],
|
||||
bgBrightBlue: [104, 49],
|
||||
bgBrightMagenta: [105, 49],
|
||||
bgBrightCyan: [106, 49],
|
||||
bgBrightWhite: [107, 49],
|
||||
|
||||
// legacy styles for colors pre v1.0.0
|
||||
blackBG: [40, 49],
|
||||
redBG: [41, 49],
|
||||
greenBG: [42, 49],
|
||||
yellowBG: [43, 49],
|
||||
blueBG: [44, 49],
|
||||
magentaBG: [45, 49],
|
||||
cyanBG: [46, 49],
|
||||
whiteBG: [47, 49],
|
||||
|
||||
};
|
||||
|
||||
Object.keys(codes).forEach(function(key) {
|
||||
var val = codes[key];
|
||||
var style = styles[key] = [];
|
||||
style.open = '\u001b[' + val[0] + 'm';
|
||||
style.close = '\u001b[' + val[1] + 'm';
|
||||
});
|
||||
@ -0,0 +1,35 @@
|
||||
/*
|
||||
MIT License
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports = function(flag, argv) {
|
||||
argv = argv || process.argv || [];
|
||||
|
||||
var terminatorPos = argv.indexOf('--');
|
||||
var prefix = /^-{1,2}/.test(flag) ? '' : '--';
|
||||
var pos = argv.indexOf(prefix + flag);
|
||||
|
||||
return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
|
||||
};
|
||||
@ -0,0 +1,151 @@
|
||||
/*
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var os = require('os');
|
||||
var hasFlag = require('./has-flag.js');
|
||||
|
||||
var env = process.env;
|
||||
|
||||
var forceColor = void 0;
|
||||
if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
|
||||
forceColor = false;
|
||||
} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true')
|
||||
|| hasFlag('color=always')) {
|
||||
forceColor = true;
|
||||
}
|
||||
if ('FORCE_COLOR' in env) {
|
||||
forceColor = env.FORCE_COLOR.length === 0
|
||||
|| parseInt(env.FORCE_COLOR, 10) !== 0;
|
||||
}
|
||||
|
||||
function translateLevel(level) {
|
||||
if (level === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
level: level,
|
||||
hasBasic: true,
|
||||
has256: level >= 2,
|
||||
has16m: level >= 3,
|
||||
};
|
||||
}
|
||||
|
||||
function supportsColor(stream) {
|
||||
if (forceColor === false) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (hasFlag('color=16m') || hasFlag('color=full')
|
||||
|| hasFlag('color=truecolor')) {
|
||||
return 3;
|
||||
}
|
||||
|
||||
if (hasFlag('color=256')) {
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (stream && !stream.isTTY && forceColor !== true) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var min = forceColor ? 1 : 0;
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
// Node.js 7.5.0 is the first version of Node.js to include a patch to
|
||||
// libuv that enables 256 color output on Windows. Anything earlier and it
|
||||
// won't work. However, here we target Node.js 8 at minimum as it is an LTS
|
||||
// release, and Node.js 7 is not. Windows 10 build 10586 is the first
|
||||
// Windows release that supports 256 colors. Windows 10 build 14931 is the
|
||||
// first release that supports 16m/TrueColor.
|
||||
var osRelease = os.release().split('.');
|
||||
if (Number(process.versions.node.split('.')[0]) >= 8
|
||||
&& Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
|
||||
return Number(osRelease[2]) >= 14931 ? 3 : 2;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
if ('CI' in env) {
|
||||
if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) {
|
||||
return sign in env;
|
||||
}) || env.CI_NAME === 'codeship') {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return min;
|
||||
}
|
||||
|
||||
if ('TEAMCITY_VERSION' in env) {
|
||||
return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0
|
||||
);
|
||||
}
|
||||
|
||||
if ('TERM_PROGRAM' in env) {
|
||||
var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
|
||||
|
||||
switch (env.TERM_PROGRAM) {
|
||||
case 'iTerm.app':
|
||||
return version >= 3 ? 3 : 2;
|
||||
case 'Hyper':
|
||||
return 3;
|
||||
case 'Apple_Terminal':
|
||||
return 2;
|
||||
// No default
|
||||
}
|
||||
}
|
||||
|
||||
if (/-256(color)?$/i.test(env.TERM)) {
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if ('COLORTERM' in env) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (env.TERM === 'dumb') {
|
||||
return min;
|
||||
}
|
||||
|
||||
return min;
|
||||
}
|
||||
|
||||
function getSupportLevel(stream) {
|
||||
var level = supportsColor(stream);
|
||||
return translateLevel(level);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
supportsColor: getSupportLevel,
|
||||
stdout: getSupportLevel(process.stdout),
|
||||
stderr: getSupportLevel(process.stderr),
|
||||
};
|
||||
@ -0,0 +1,45 @@
|
||||
{
|
||||
"name": "@colors/colors",
|
||||
"description": "get colors in your node.js console",
|
||||
"version": "1.6.0",
|
||||
"author": "DABH",
|
||||
"contributors": [
|
||||
{
|
||||
"name": "DABH",
|
||||
"url": "https://github.com/DABH"
|
||||
}
|
||||
],
|
||||
"homepage": "https://github.com/DABH/colors.js",
|
||||
"bugs": "https://github.com/DABH/colors.js/issues",
|
||||
"keywords": [
|
||||
"ansi",
|
||||
"terminal",
|
||||
"colors"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "http://github.com/DABH/colors.js.git"
|
||||
},
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"lint": "eslint . --fix",
|
||||
"test": "export FORCE_COLOR=1 && node tests/basic-test.js && node tests/safe-test.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.1.90"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"files": [
|
||||
"examples",
|
||||
"lib",
|
||||
"LICENSE",
|
||||
"safe.js",
|
||||
"themes",
|
||||
"index.d.ts",
|
||||
"safe.d.ts"
|
||||
],
|
||||
"devDependencies": {
|
||||
"eslint": "^8.9.0",
|
||||
"eslint-config-google": "^0.14.0"
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,64 @@
|
||||
// Type definitions for Colors.js 1.2
|
||||
// Project: https://github.com/Marak/colors.js
|
||||
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Staffan Eketorp <https://github.com/staeke>
|
||||
// Definitions: https://github.com/Marak/colors.js
|
||||
|
||||
export const enabled: boolean;
|
||||
export function enable(): void;
|
||||
export function disable(): void;
|
||||
export function setTheme(theme: any): void;
|
||||
|
||||
export function strip(str: string): string;
|
||||
export function stripColors(str: string): string;
|
||||
|
||||
export function black(str: string): string;
|
||||
export function red(str: string): string;
|
||||
export function green(str: string): string;
|
||||
export function yellow(str: string): string;
|
||||
export function blue(str: string): string;
|
||||
export function magenta(str: string): string;
|
||||
export function cyan(str: string): string;
|
||||
export function white(str: string): string;
|
||||
export function gray(str: string): string;
|
||||
export function grey(str: string): string;
|
||||
|
||||
export function brightRed(str: string): string;
|
||||
export function brightGreen(str: string): string;
|
||||
export function brightYellow(str: string): string;
|
||||
export function brightBlue(str: string): string;
|
||||
export function brightMagenta(str: string): string;
|
||||
export function brightCyan(str: string): string;
|
||||
export function brightWhite(str: string): string;
|
||||
|
||||
export function bgBlack(str: string): string;
|
||||
export function bgRed(str: string): string;
|
||||
export function bgGreen(str: string): string;
|
||||
export function bgYellow(str: string): string;
|
||||
export function bgBlue(str: string): string;
|
||||
export function bgMagenta(str: string): string;
|
||||
export function bgCyan(str: string): string;
|
||||
export function bgWhite(str: string): string;
|
||||
|
||||
export function bgBrightRed(str: string): string;
|
||||
export function bgBrightGreen(str: string): string;
|
||||
export function bgBrightYellow(str: string): string;
|
||||
export function bgBrightBlue(str: string): string;
|
||||
export function bgBrightMagenta(str: string): string;
|
||||
export function bgBrightCyan(str: string): string;
|
||||
export function bgBrightWhite(str: string): string;
|
||||
|
||||
export function reset(str: string): string;
|
||||
export function bold(str: string): string;
|
||||
export function dim(str: string): string;
|
||||
export function italic(str: string): string;
|
||||
export function underline(str: string): string;
|
||||
export function inverse(str: string): string;
|
||||
export function hidden(str: string): string;
|
||||
export function strikethrough(str: string): string;
|
||||
|
||||
export function rainbow(str: string): string;
|
||||
export function zebra(str: string): string;
|
||||
export function america(str: string): string;
|
||||
export function trap(str: string): string;
|
||||
export function random(str: string): string;
|
||||
export function zalgo(str: string): string;
|
||||
@ -0,0 +1,10 @@
|
||||
//
|
||||
// Remark: Requiring this file will use the "safe" colors API,
|
||||
// which will not touch String.prototype.
|
||||
//
|
||||
// var colors = require('colors/safe');
|
||||
// colors.red("foo")
|
||||
//
|
||||
//
|
||||
var colors = require('./lib/colors');
|
||||
module['exports'] = colors;
|
||||
@ -0,0 +1,12 @@
|
||||
module['exports'] = {
|
||||
silly: 'rainbow',
|
||||
input: 'grey',
|
||||
verbose: 'cyan',
|
||||
prompt: 'grey',
|
||||
info: 'green',
|
||||
data: 'grey',
|
||||
help: 'cyan',
|
||||
warn: 'yellow',
|
||||
debug: 'blue',
|
||||
error: 'red',
|
||||
};
|
||||
@ -0,0 +1,26 @@
|
||||
# CHANGELOG
|
||||
|
||||
### 2.0.2
|
||||
|
||||
- Bump to kuler 2.0, which removes colornames as dependency, which we
|
||||
never used. So smaller install size, less dependencies for all.
|
||||
|
||||
### 2.0.1
|
||||
|
||||
- Use `storag-engine@3.0` which will automatically detect the correct
|
||||
AsyncStorage implementation.
|
||||
- The upgrade also fixes a bug where it the `debug` and `diagnostics` values
|
||||
to be JSON encoded instead of regular plain text.
|
||||
|
||||
### 2.0.0
|
||||
|
||||
- Documentation improvements.
|
||||
- Fixed a issue where async adapters were incorrectly detected.
|
||||
- Correctly inherit colors after applying colors the browser's console.
|
||||
|
||||
### 2.0.0-alpha
|
||||
|
||||
- Complete rewrite of all internals, now comes with separate builds for `browser`
|
||||
`node` and `react-native` as well as dedicated builds for `production` and
|
||||
`development` environments. Various utility methods and properties have
|
||||
been added to the returned logger to make your lives even easier.
|
||||
@ -0,0 +1,20 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Arnout Kazemier, Martijn Swaagman, the Contributors.
|
||||
|
||||
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.
|
||||
@ -0,0 +1,473 @@
|
||||
# `diagnostics`
|
||||
|
||||
Diagnostics in the evolution of debug pattern that is used in the Node.js core,
|
||||
this extremely small but powerful technique can best be compared as feature
|
||||
flags for loggers. The created debug logger is disabled by default but can be
|
||||
enabled without changing a line of code, using flags.
|
||||
|
||||
- Allows debugging in multiple JavaScript environments such as Node.js, browsers
|
||||
and React-Native.
|
||||
- Separated development and production builds to minimize impact on your
|
||||
application when bundled.
|
||||
- Allows for customization of logger, messages, and much more.
|
||||
|
||||

|
||||
|
||||
## Installation
|
||||
|
||||
The module is released in the public npm registry and can be installed by
|
||||
running:
|
||||
|
||||
```
|
||||
npm install --save @dabh/diagnostics
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
- [Introduction](#introduction)
|
||||
- [Advanced usage](#advanced-usage)
|
||||
- [Production and development builds](#production-and-development-builds)
|
||||
- [WebPack](#webpack)
|
||||
- [Node.js](#nodejs)
|
||||
- [API](#api)
|
||||
- [.enabled](#enabled)
|
||||
- [.namespace](#namespace)
|
||||
- [.dev/prod](#devprod)
|
||||
- [set](#set)
|
||||
- [modify](#modify)
|
||||
- [use](#use)
|
||||
- [Modifiers](#modifiers)
|
||||
- [namespace](#namespace-1)
|
||||
- [Adapters](#adapters)
|
||||
- [process.env](#process-env)
|
||||
- [hash](#hash)
|
||||
- [localStorage](#localstorage)
|
||||
- [AsyncStorage](#asyncstorage)
|
||||
- [Loggers](#loggers)
|
||||
|
||||
### Introduction
|
||||
|
||||
To create a new logger simply `require` the `@dabh/diagnostics` module and call
|
||||
the returned function. It accepts 2 arguments:
|
||||
|
||||
1. `namespace` **Required** This is the namespace of your logger so we know if we need to
|
||||
enable your logger when a debug flag is used. Generally you use the name of
|
||||
your library or application as first root namespace. For example if you're
|
||||
building a parser in a library (example) you would set namespace
|
||||
`example:parser`.
|
||||
2. `options` An object with additional configuration for the logger.
|
||||
following keys are recognized:
|
||||
- `force` Force the logger to be enabled.
|
||||
- `colors` Colors are enabled by default for the logs, but you can set this
|
||||
option to `false` to disable it.
|
||||
|
||||
```js
|
||||
const debug = require('@dabh/diagnostics')('foo:bar:baz');
|
||||
const debug = require('@dabh/diagnostics')('foo:bar:baz', { options });
|
||||
|
||||
debug('this is a log message %s', 'that will only show up when enabled');
|
||||
debug('that is pretty neat', { log: 'more', data: 1337 });
|
||||
```
|
||||
|
||||
Unlike `console.log` statements that add and remove during your development
|
||||
lifecycle you create meaningful log statements that will give you insight in
|
||||
the library or application that you're developing.
|
||||
|
||||
The created debugger uses different "adapters" to extract the debug flag
|
||||
out of the JavaScript environment. To learn more about enabling the debug flag
|
||||
in your specific environment click on one of the enabled adapters below.
|
||||
|
||||
- **browser**: [localStorage](#localstorage), [hash](#hash)
|
||||
- **node.js**: [environment variables](#processenv)
|
||||
- **react-native**: [AsyncStorage](#asyncstorage)
|
||||
|
||||
Please note that the returned logger is fully configured out of the box, you
|
||||
do not need to set any of the adapters/modifiers your self, they are there
|
||||
for when you want more advanced control over the process. But if you want to
|
||||
learn more about that, read the next section.
|
||||
|
||||
### Advanced usage
|
||||
|
||||
There are 2 specific usage patterns for `diagnostic`, library developers who
|
||||
implement it as part of their modules and applications developers who either
|
||||
use it in their application or are searching for ways to consume the messages.
|
||||
|
||||
With the simple log interface as discussed in the [introduction](#introduction)
|
||||
section we make it easy for developers to add it as part of their libraries
|
||||
and applications, and with powerful [API](#api) we allow infinite customization
|
||||
by allowing custom adapters, loggers and modifiers to ensure that this library
|
||||
maintains relevant. These methods not only allow introduction of new loggers,
|
||||
but allow you think outside the box. For example you can maintain a history
|
||||
of past log messages, and output those when an uncaught exception happens in
|
||||
your application so you have additional context
|
||||
|
||||
```js
|
||||
const diagnostics = require('@dabh/diagnostics');
|
||||
|
||||
let index = 0;
|
||||
const limit = 200;
|
||||
const history = new Array(limit);
|
||||
|
||||
//
|
||||
// Force all `diagnostic` loggers to be enabled.
|
||||
//
|
||||
diagnostics.force = process.env.NODE_ENV === 'prod';
|
||||
diagnostics.set(function customLogger(meta, message) {
|
||||
history[index]= { meta, message, now: Date.now() };
|
||||
if (index++ === limit) index = 0;
|
||||
|
||||
//
|
||||
// We're running a development build, so output.
|
||||
//
|
||||
if (meta.dev) console.log.apply(console, message);
|
||||
});
|
||||
|
||||
process.on('uncaughtException', async function (err) {
|
||||
await saveErrorToDisk(err, history);
|
||||
process.exit(1);
|
||||
});
|
||||
```
|
||||
|
||||
The small snippet above will maintain a 200 limited FIFO (First In First Out)
|
||||
queue of all debug messages that can be referenced when your application crashes
|
||||
|
||||
#### Production and development builds
|
||||
|
||||
When you `require` the `@dabh/diagnostics` module you will be given a logger that is
|
||||
optimized for `development` so it can provide the best developer experience
|
||||
possible.
|
||||
|
||||
The development logger enables all the [adapters](#adapters) for your
|
||||
JavaScript environment, adds a logger that outputs the messages to `console.log`
|
||||
and registers our message modifiers so log messages will be prefixed with the
|
||||
supplied namespace so you know where the log messages originates from.
|
||||
|
||||
The development logger does not have any adapter, modifier and logger enabled
|
||||
by default. This ensures that your log messages never accidentally show up in
|
||||
production. However this does not mean that it's not possible to get debug
|
||||
messages in production. You can `force` the debugger to be enabled, and
|
||||
supply a [custom logger](#loggers).
|
||||
|
||||
```js
|
||||
const diagnostics = require('@dabh/diagnostics');
|
||||
const debug = debug('foo:bar', { force: true });
|
||||
|
||||
//
|
||||
// Or enable _every_ diagnostic instance:
|
||||
//
|
||||
diagnostics.force = true;
|
||||
```
|
||||
|
||||
##### WebPack
|
||||
|
||||
WebPack has the concept of [mode](https://webpack.js.org/concepts/mode/#usage)'s
|
||||
which creates different
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
mode: 'development' // 'production'
|
||||
}
|
||||
```
|
||||
|
||||
When you are building your app using the WebPack CLI you can use the `--mode`
|
||||
flag:
|
||||
|
||||
```
|
||||
webpack --mode=production app.js -o /dist/bundle.js
|
||||
```
|
||||
|
||||
##### Node.js
|
||||
|
||||
When you are running your app using `Node.js` you should the `NODE_ENV`
|
||||
environment variable to `production` to ensure that you libraries that you
|
||||
import are optimized for production.
|
||||
|
||||
```
|
||||
NODE_ENV=production node app.js
|
||||
```
|
||||
|
||||
### API
|
||||
|
||||
The returned logger exposes some addition properties that can be used used in
|
||||
your application or library:
|
||||
|
||||
#### .enabled
|
||||
|
||||
The returned logger will have a `.enabled` property assigned to it. This boolean
|
||||
can be used to check if the logger was enabled:
|
||||
|
||||
```js
|
||||
const debug = require('@dabh/diagnostics')('foo:bar');
|
||||
|
||||
if (debug.enabled) {
|
||||
//
|
||||
// Do something special
|
||||
//
|
||||
}
|
||||
```
|
||||
|
||||
This property is exposed as:
|
||||
|
||||
- Property on the logger.
|
||||
- Property on the meta/options object.
|
||||
|
||||
#### .namespace
|
||||
|
||||
This is the namespace that you originally provided to the function.
|
||||
|
||||
```js
|
||||
const debug = require('@dabh/diagnostics')('foo:bar');
|
||||
|
||||
console.log(debug.namespace); // foo:bar
|
||||
```
|
||||
|
||||
This property is exposed as:
|
||||
|
||||
- Property on the logger.
|
||||
- Property on the meta/options object.
|
||||
|
||||
#### .dev/prod
|
||||
|
||||
There are different builds available of `diagnostics`, when you create a
|
||||
production build of your application using `NODE_ENV=production` you will be
|
||||
given an optimized, smaller build of `diagnostics` to reduce your bundle size.
|
||||
The `dev` and `prod` booleans on the returned logger indicate if you have a
|
||||
production or development version of the logger.
|
||||
|
||||
```js
|
||||
const debug = require('@dabh/diagnostics')('foo:bar');
|
||||
|
||||
if (debug.prod) {
|
||||
// do stuff
|
||||
}
|
||||
```
|
||||
|
||||
This property is exposed as:
|
||||
|
||||
- Property on the logger.
|
||||
- Property on the meta/options object.
|
||||
|
||||
#### set
|
||||
|
||||
Sets a new logger as default for **all** `diagnostic` instances. The passed
|
||||
argument should be a function that write the log messages to where ever you
|
||||
want. It receives 2 arguments:
|
||||
|
||||
1. `meta` An object with all the options that was provided to the original
|
||||
logger that wants to write the log message as well as properties of the
|
||||
debugger such as `prod`, `dev`, `namespace`, `enabled`. See [API](#api) for
|
||||
all exposed properties.
|
||||
2. `args` An array of the log messages that needs to be written.
|
||||
|
||||
```js
|
||||
const debug = require('@dabh/diagnostics')('foo:more:namespaces');
|
||||
|
||||
debug.use(function logger(meta, args) {
|
||||
console.log(meta);
|
||||
console.debug(...args);
|
||||
});
|
||||
```
|
||||
|
||||
This method is exposed as:
|
||||
|
||||
- Method on the logger.
|
||||
- Method on the meta/options object.
|
||||
- Method on `diagnostics` module.
|
||||
|
||||
#### modify
|
||||
|
||||
The modify method allows you add a new message modifier to **all** `diagnostic`
|
||||
instances. The passed argument should be a function that returns the passed
|
||||
message after modification. The function receives 2 arguments:
|
||||
|
||||
1. `message`, Array, the log message.
|
||||
2. `options`, Object, the options that were passed into the logger when it was
|
||||
initially created.
|
||||
|
||||
```js
|
||||
const debug = require('@dabh/diagnostics')('example:modifiers');
|
||||
|
||||
debug.modify(function (message, options) {
|
||||
return messages;
|
||||
});
|
||||
```
|
||||
|
||||
This method is exposed as:
|
||||
|
||||
- Method on the logger.
|
||||
- Method on the meta/options object.
|
||||
- Method on `diagnostics` module.
|
||||
|
||||
See [modifiers](#modifiers) for more information.
|
||||
|
||||
#### use
|
||||
|
||||
Adds a new `adapter` to **all** `diagnostic` instances. The passed argument
|
||||
should be a function returns a boolean that indicates if the passed in
|
||||
`namespace` is allowed to write log messages.
|
||||
|
||||
```js
|
||||
const diagnostics = require('@dabh/diagnostics');
|
||||
const debug = diagnostics('foo:bar');
|
||||
|
||||
debug.use(function (namespace) {
|
||||
return namespace === 'foo:bar';
|
||||
});
|
||||
```
|
||||
|
||||
This method is exposed as:
|
||||
|
||||
- Method on the logger.
|
||||
- Method on the meta/options object.
|
||||
- Method on `diagnostics` module.
|
||||
|
||||
See [adapters](#adapters) for more information.
|
||||
|
||||
### Modifiers
|
||||
|
||||
To be as flexible as possible when it comes to transforming messages we've
|
||||
come up with the concept of `modifiers` which can enhance the debug messages.
|
||||
This allows you to introduce functionality or details that you find important
|
||||
for debug messages, and doesn't require us to add additional bloat to the
|
||||
`diagnostic` core.
|
||||
|
||||
For example, you want the messages to be prefixed with the date-time of when
|
||||
the log message occured:
|
||||
|
||||
```js
|
||||
const diagnostics = require('@dabh/diagnostics');
|
||||
|
||||
diagnostics.modify(function datetime(args, options) {
|
||||
args.unshift(new Date());
|
||||
return args;
|
||||
});
|
||||
```
|
||||
|
||||
Now all messages will be prefixed with date that is outputted by `new Date()`.
|
||||
The following modifiers are shipped with `diagnostics` and are enabled in
|
||||
**development** mode only:
|
||||
|
||||
- [namespace](#namespace)
|
||||
|
||||
#### namespace
|
||||
|
||||
This modifier is enabled for all debug instances and prefixes the messages
|
||||
with the name of namespace under which it is logged. The namespace is colored
|
||||
using the `colorspace` module which groups similar namespaces under the same
|
||||
colorspace. You can have multiple namespaces for the debuggers where each
|
||||
namespace should be separated by a `:`
|
||||
|
||||
```
|
||||
foo
|
||||
foo:bar
|
||||
foo:bar:baz
|
||||
```
|
||||
|
||||
For console based output the `namespace-ansi` is used.
|
||||
|
||||
### Adapters
|
||||
|
||||
Adapters allows `diagnostics` to pull the `DEBUG` and `DIAGNOSTICS` environment
|
||||
variables from different sources. Not every JavaScript environment has a
|
||||
`process.env` that we can leverage. Adapters allows us to have different
|
||||
adapters for different environments. It means you can write your own custom
|
||||
adapter if needed as well.
|
||||
|
||||
The `adapter` function should be passed a function as argument, this function
|
||||
will receive the `namespace` of a logger as argument and it should return a
|
||||
boolean that indicates if that logger should be enabled or not.
|
||||
|
||||
```js
|
||||
const debug = require('@dabh/diagnostics')('example:namespace');
|
||||
|
||||
debug.adapter(require('@dabh/diagnostics/adapters/localstorage'));
|
||||
```
|
||||
|
||||
The modifiers are only enabled for `development`. The following adapters are
|
||||
available are available:
|
||||
|
||||
#### process.env
|
||||
|
||||
This adapter is enabled for `node.js`.
|
||||
|
||||
Uses the `DEBUG` or `DIAGNOSTICS` (both are recognized) environment variables to
|
||||
pass in debug flag:
|
||||
|
||||
**UNIX/Linux/Mac**
|
||||
```
|
||||
DEBUG=foo* node index.js
|
||||
```
|
||||
|
||||
Using environment variables on Windows is a bit different, and also depends on
|
||||
toolchain you are using:
|
||||
|
||||
**Windows**
|
||||
```
|
||||
set DEBUG=foo* & node index.js
|
||||
```
|
||||
|
||||
**Powershell**
|
||||
```
|
||||
$env:DEBUG='foo*';node index.js
|
||||
```
|
||||
|
||||
#### hash
|
||||
|
||||
This adapter is enabled for `browsers`.
|
||||
|
||||
This adapter uses the `window.location.hash` of as source for the environment
|
||||
variables. It assumes that hash is formatted using the same syntax as query
|
||||
strings:
|
||||
|
||||
```js
|
||||
http://example.com/foo/bar#debug=foo*
|
||||
```
|
||||
|
||||
It triggers on both the `debug=` and `diagnostics=` names.
|
||||
|
||||
#### localStorage
|
||||
|
||||
This adapter is enabled for `browsers`.
|
||||
|
||||
This adapter uses the `localStorage` of the browser to store the debug flags.
|
||||
You can set the debug flag your self in your application code, but you can
|
||||
also open browser WebInspector and enable it through the console.
|
||||
|
||||
```js
|
||||
localStorage.setItem('debug', 'foo*');
|
||||
```
|
||||
|
||||
It triggers on both the `debug` and `diagnostics` storage items. (Please note
|
||||
that these keys should be entered in lowercase)
|
||||
|
||||
#### AsyncStorage
|
||||
|
||||
This adapter is enabled for `react-native`.
|
||||
|
||||
This adapter uses the `AsyncStorage` API that is exposed by the `react-native`
|
||||
library to store and read the `debug` or `diagnostics` storage items.
|
||||
|
||||
```js
|
||||
import { AsyncStorage } from 'react-native';
|
||||
|
||||
AsyncStorage.setItem('debug', 'foo*');
|
||||
```
|
||||
|
||||
Unlike other adapters, this is the only adapter that is `async` so that means
|
||||
that we're not able to instantly determine if a created logger should be
|
||||
enabled or disabled. So when a logger is created in `react-native` we initially
|
||||
assume it's disabled, any message that send during period will be queued
|
||||
internally.
|
||||
|
||||
Once we've received the data from the `AsyncStorage` API we will determine
|
||||
if the logger should be enabled, flush the queued messages if needed and set
|
||||
all `enabled` properties accordingly on the returned logger.
|
||||
|
||||
### Loggers
|
||||
|
||||
By default it will log all messages to `console.log` in when the logger is
|
||||
enabled using the debug flag that is set using one of the adapters.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
@ -0,0 +1,11 @@
|
||||
var adapter = require('./');
|
||||
|
||||
/**
|
||||
* Extracts the values from process.env.
|
||||
*
|
||||
* @type {Function}
|
||||
* @public
|
||||
*/
|
||||
module.exports = adapter(function hash() {
|
||||
return /(debug|diagnostics)=([^&]+)/i.exec(window.location.hash)[2];
|
||||
});
|
||||
@ -0,0 +1,18 @@
|
||||
var enabled = require('enabled');
|
||||
|
||||
/**
|
||||
* Creates a new Adapter.
|
||||
*
|
||||
* @param {Function} fn Function that returns the value.
|
||||
* @returns {Function} The adapter logic.
|
||||
* @public
|
||||
*/
|
||||
module.exports = function create(fn) {
|
||||
return function adapter(namespace) {
|
||||
try {
|
||||
return enabled(namespace, fn());
|
||||
} catch (e) { /* Any failure means that we found nothing */ }
|
||||
|
||||
return false;
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
var adapter = require('./');
|
||||
|
||||
/**
|
||||
* Extracts the values from process.env.
|
||||
*
|
||||
* @type {Function}
|
||||
* @public
|
||||
*/
|
||||
module.exports = adapter(function storage() {
|
||||
return localStorage.getItem('debug') || localStorage.getItem('diagnostics');
|
||||
});
|
||||
@ -0,0 +1,11 @@
|
||||
var adapter = require('./');
|
||||
|
||||
/**
|
||||
* Extracts the values from process.env.
|
||||
*
|
||||
* @type {Function}
|
||||
* @public
|
||||
*/
|
||||
module.exports = adapter(function processenv() {
|
||||
return process.env.DEBUG || process.env.DIAGNOSTICS;
|
||||
});
|
||||
@ -0,0 +1,35 @@
|
||||
var create = require('../diagnostics');
|
||||
|
||||
/**
|
||||
* Create a new diagnostics logger.
|
||||
*
|
||||
* @param {String} namespace The namespace it should enable.
|
||||
* @param {Object} options Additional options.
|
||||
* @returns {Function} The logger.
|
||||
* @public
|
||||
*/
|
||||
var diagnostics = create(function dev(namespace, options) {
|
||||
options = options || {};
|
||||
options.namespace = namespace;
|
||||
options.prod = false;
|
||||
options.dev = true;
|
||||
|
||||
if (!dev.enabled(namespace) && !(options.force || dev.force)) {
|
||||
return dev.nope(options);
|
||||
}
|
||||
|
||||
return dev.yep(options);
|
||||
});
|
||||
|
||||
//
|
||||
// Configure the logger for the given environment.
|
||||
//
|
||||
diagnostics.modify(require('../modifiers/namespace'));
|
||||
diagnostics.use(require('../adapters/localstorage'));
|
||||
diagnostics.use(require('../adapters/hash'));
|
||||
diagnostics.set(require('../logger/console'));
|
||||
|
||||
//
|
||||
// Expose the diagnostics logger.
|
||||
//
|
||||
module.exports = diagnostics;
|
||||
@ -0,0 +1,8 @@
|
||||
//
|
||||
// Select the correct build version depending on the environment.
|
||||
//
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
module.exports = require('./production.js');
|
||||
} else {
|
||||
module.exports = require('./development.js');
|
||||
}
|
||||
@ -0,0 +1,6 @@
|
||||
var diagnostics = require('./');
|
||||
|
||||
//
|
||||
// No way to override `debug` with `diagnostics` in the browser.
|
||||
//
|
||||
module.exports = diagnostics;
|
||||
@ -0,0 +1,24 @@
|
||||
var create = require('../diagnostics');
|
||||
|
||||
/**
|
||||
* Create a new diagnostics logger.
|
||||
*
|
||||
* @param {String} namespace The namespace it should enable.
|
||||
* @param {Object} options Additional options.
|
||||
* @returns {Function} The logger.
|
||||
* @public
|
||||
*/
|
||||
var diagnostics = create(function prod(namespace, options) {
|
||||
options = options || {};
|
||||
options.namespace = namespace;
|
||||
options.prod = true;
|
||||
options.dev = false;
|
||||
|
||||
if (!(options.force || prod.force)) return prod.nope(options);
|
||||
return prod.yep(options);
|
||||
});
|
||||
|
||||
//
|
||||
// Expose the diagnostics logger.
|
||||
//
|
||||
module.exports = diagnostics;
|
||||
@ -0,0 +1,212 @@
|
||||
/**
|
||||
* Contains all configured adapters for the given environment.
|
||||
*
|
||||
* @type {Array}
|
||||
* @public
|
||||
*/
|
||||
var adapters = [];
|
||||
|
||||
/**
|
||||
* Contains all modifier functions.
|
||||
*
|
||||
* @typs {Array}
|
||||
* @public
|
||||
*/
|
||||
var modifiers = [];
|
||||
|
||||
/**
|
||||
* Our default logger.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
var logger = function devnull() {};
|
||||
|
||||
/**
|
||||
* Register a new adapter that will used to find environments.
|
||||
*
|
||||
* @param {Function} adapter A function that will return the possible env.
|
||||
* @returns {Boolean} Indication of a successful add.
|
||||
* @public
|
||||
*/
|
||||
function use(adapter) {
|
||||
if (~adapters.indexOf(adapter)) return false;
|
||||
|
||||
adapters.push(adapter);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign a new log method.
|
||||
*
|
||||
* @param {Function} custom The log method.
|
||||
* @public
|
||||
*/
|
||||
function set(custom) {
|
||||
logger = custom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the namespace is allowed by any of our adapters.
|
||||
*
|
||||
* @param {String} namespace The namespace that needs to be enabled
|
||||
* @returns {Boolean|Promise} Indication if the namespace is enabled by our adapters.
|
||||
* @public
|
||||
*/
|
||||
function enabled(namespace) {
|
||||
var async = [];
|
||||
|
||||
for (var i = 0; i < adapters.length; i++) {
|
||||
if (adapters[i].async) {
|
||||
async.push(adapters[i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (adapters[i](namespace)) return true;
|
||||
}
|
||||
|
||||
if (!async.length) return false;
|
||||
|
||||
//
|
||||
// Now that we know that we Async functions, we know we run in an ES6
|
||||
// environment and can use all the API's that they offer, in this case
|
||||
// we want to return a Promise so that we can `await` in React-Native
|
||||
// for an async adapter.
|
||||
//
|
||||
return new Promise(function pinky(resolve) {
|
||||
Promise.all(
|
||||
async.map(function prebind(fn) {
|
||||
return fn(namespace);
|
||||
})
|
||||
).then(function resolved(values) {
|
||||
resolve(values.some(Boolean));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new message modifier to the debugger.
|
||||
*
|
||||
* @param {Function} fn Modification function.
|
||||
* @returns {Boolean} Indication of a successful add.
|
||||
* @public
|
||||
*/
|
||||
function modify(fn) {
|
||||
if (~modifiers.indexOf(fn)) return false;
|
||||
|
||||
modifiers.push(fn);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data to the supplied logger.
|
||||
*
|
||||
* @param {Object} meta Meta information about the log.
|
||||
* @param {Array} args Arguments for console.log.
|
||||
* @public
|
||||
*/
|
||||
function write() {
|
||||
logger.apply(logger, arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the message with the modifiers.
|
||||
*
|
||||
* @param {Mixed} message The message to be transformed by modifers.
|
||||
* @returns {String} Transformed message.
|
||||
* @public
|
||||
*/
|
||||
function process(message) {
|
||||
for (var i = 0; i < modifiers.length; i++) {
|
||||
message = modifiers[i].apply(modifiers[i], arguments);
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Introduce options to the logger function.
|
||||
*
|
||||
* @param {Function} fn Calback function.
|
||||
* @param {Object} options Properties to introduce on fn.
|
||||
* @returns {Function} The passed function
|
||||
* @public
|
||||
*/
|
||||
function introduce(fn, options) {
|
||||
var has = Object.prototype.hasOwnProperty;
|
||||
|
||||
for (var key in options) {
|
||||
if (has.call(options, key)) {
|
||||
fn[key] = options[key];
|
||||
}
|
||||
}
|
||||
|
||||
return fn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nope, we're not allowed to write messages.
|
||||
*
|
||||
* @returns {Boolean} false
|
||||
* @public
|
||||
*/
|
||||
function nope(options) {
|
||||
options.enabled = false;
|
||||
options.modify = modify;
|
||||
options.set = set;
|
||||
options.use = use;
|
||||
|
||||
return introduce(function diagnopes() {
|
||||
return false;
|
||||
}, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Yep, we're allowed to write debug messages.
|
||||
*
|
||||
* @param {Object} options The options for the process.
|
||||
* @returns {Function} The function that does the logging.
|
||||
* @public
|
||||
*/
|
||||
function yep(options) {
|
||||
/**
|
||||
* The function that receives the actual debug information.
|
||||
*
|
||||
* @returns {Boolean} indication that we're logging.
|
||||
* @public
|
||||
*/
|
||||
function diagnostics() {
|
||||
var args = Array.prototype.slice.call(arguments, 0);
|
||||
|
||||
write.call(write, options, process(args, options));
|
||||
return true;
|
||||
}
|
||||
|
||||
options.enabled = true;
|
||||
options.modify = modify;
|
||||
options.set = set;
|
||||
options.use = use;
|
||||
|
||||
return introduce(diagnostics, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple helper function to introduce various of helper methods to our given
|
||||
* diagnostics function.
|
||||
*
|
||||
* @param {Function} diagnostics The diagnostics function.
|
||||
* @returns {Function} diagnostics
|
||||
* @public
|
||||
*/
|
||||
module.exports = function create(diagnostics) {
|
||||
diagnostics.introduce = introduce;
|
||||
diagnostics.enabled = enabled;
|
||||
diagnostics.process = process;
|
||||
diagnostics.modify = modify;
|
||||
diagnostics.write = write;
|
||||
diagnostics.nope = nope;
|
||||
diagnostics.yep = yep;
|
||||
diagnostics.set = set;
|
||||
diagnostics.use = use;
|
||||
|
||||
return diagnostics;
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
/**
|
||||
* An idiot proof logger to be used as default. We've wrapped it in a try/catch
|
||||
* statement to ensure the environments without the `console` API do not crash
|
||||
* as well as an additional fix for ancient browsers like IE8 where the
|
||||
* `console.log` API doesn't have an `apply`, so we need to use the Function's
|
||||
* apply functionality to apply the arguments.
|
||||
*
|
||||
* @param {Object} meta Options of the logger.
|
||||
* @param {Array} messages The actuall message that needs to be logged.
|
||||
* @public
|
||||
*/
|
||||
module.exports = function (meta, messages) {
|
||||
//
|
||||
// So yea. IE8 doesn't have an apply so we need a work around to puke the
|
||||
// arguments in place.
|
||||
//
|
||||
try { Function.prototype.apply.call(console.log, console, messages); }
|
||||
catch (e) {}
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
var colorspace = require('colorspace');
|
||||
var kuler = require('kuler');
|
||||
|
||||
/**
|
||||
* Prefix the messages with a colored namespace.
|
||||
*
|
||||
* @param {Array} args The messages array that is getting written.
|
||||
* @param {Object} options Options for diagnostics.
|
||||
* @returns {Array} Altered messages array.
|
||||
* @public
|
||||
*/
|
||||
module.exports = function ansiModifier(args, options) {
|
||||
var namespace = options.namespace;
|
||||
var ansi = options.colors !== false
|
||||
? kuler(namespace +':', colorspace(namespace))
|
||||
: namespace +':';
|
||||
|
||||
args[0] = ansi +' '+ args[0];
|
||||
return args;
|
||||
};
|
||||
@ -0,0 +1,32 @@
|
||||
var colorspace = require('colorspace');
|
||||
|
||||
/**
|
||||
* Prefix the messages with a colored namespace.
|
||||
*
|
||||
* @param {Array} messages The messages array that is getting written.
|
||||
* @param {Object} options Options for diagnostics.
|
||||
* @returns {Array} Altered messages array.
|
||||
* @public
|
||||
*/
|
||||
module.exports = function colorNamespace(args, options) {
|
||||
var namespace = options.namespace;
|
||||
|
||||
if (options.colors === false) {
|
||||
args[0] = namespace +': '+ args[0];
|
||||
return args;
|
||||
}
|
||||
|
||||
var color = colorspace(namespace);
|
||||
|
||||
//
|
||||
// The console API supports a special %c formatter in browsers. This is used
|
||||
// to style console messages with any CSS styling, in our case we want to
|
||||
// use colorize the namespace for clarity. As these are formatters, and
|
||||
// we need to inject our CSS string as second messages argument so it
|
||||
// gets picked up correctly.
|
||||
//
|
||||
args[0] = '%c'+ namespace +':%c '+ args[0];
|
||||
args.splice(1, 0, 'color:'+ color, 'color:inherit');
|
||||
|
||||
return args;
|
||||
};
|
||||
@ -0,0 +1,36 @@
|
||||
var create = require('../diagnostics');
|
||||
var tty = require('tty').isatty(1);
|
||||
|
||||
/**
|
||||
* Create a new diagnostics logger.
|
||||
*
|
||||
* @param {String} namespace The namespace it should enable.
|
||||
* @param {Object} options Additional options.
|
||||
* @returns {Function} The logger.
|
||||
* @public
|
||||
*/
|
||||
var diagnostics = create(function dev(namespace, options) {
|
||||
options = options || {};
|
||||
options.colors = 'colors' in options ? options.colors : tty;
|
||||
options.namespace = namespace;
|
||||
options.prod = false;
|
||||
options.dev = true;
|
||||
|
||||
if (!dev.enabled(namespace) && !(options.force || dev.force)) {
|
||||
return dev.nope(options);
|
||||
}
|
||||
|
||||
return dev.yep(options);
|
||||
});
|
||||
|
||||
//
|
||||
// Configure the logger for the given environment.
|
||||
//
|
||||
diagnostics.modify(require('../modifiers/namespace-ansi'));
|
||||
diagnostics.use(require('../adapters/process.env'));
|
||||
diagnostics.set(require('../logger/console'));
|
||||
|
||||
//
|
||||
// Expose the diagnostics logger.
|
||||
//
|
||||
module.exports = diagnostics;
|
||||
@ -0,0 +1,8 @@
|
||||
//
|
||||
// Select the correct build version depending on the environment.
|
||||
//
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
module.exports = require('./production.js');
|
||||
} else {
|
||||
module.exports = require('./development.js');
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
const diagnostics = require('./');
|
||||
|
||||
//
|
||||
// Override the existing `debug` call so it will use `diagnostics` instead
|
||||
// of the `debug` module.
|
||||
//
|
||||
try {
|
||||
var key = require.resolve('debug');
|
||||
|
||||
require.cache[key] = {
|
||||
exports: diagnostics,
|
||||
filename: key,
|
||||
loaded: true,
|
||||
id: key
|
||||
};
|
||||
} catch (e) { /* We don't really care if it fails */ }
|
||||
|
||||
//
|
||||
// Export the default import as exports again.
|
||||
//
|
||||
module.exports = diagnostics;
|
||||
@ -0,0 +1,24 @@
|
||||
var create = require('../diagnostics');
|
||||
|
||||
/**
|
||||
* Create a new diagnostics logger.
|
||||
*
|
||||
* @param {String} namespace The namespace it should enable.
|
||||
* @param {Object} options Additional options.
|
||||
* @returns {Function} The logger.
|
||||
* @public
|
||||
*/
|
||||
var diagnostics = create(function prod(namespace, options) {
|
||||
options = options || {};
|
||||
options.namespace = namespace;
|
||||
options.prod = true;
|
||||
options.dev = false;
|
||||
|
||||
if (!(options.force || prod.force)) return prod.nope(options);
|
||||
return prod.yep(options);
|
||||
});
|
||||
|
||||
//
|
||||
// Expose the diagnostics logger.
|
||||
//
|
||||
module.exports = diagnostics;
|
||||
@ -0,0 +1,64 @@
|
||||
{
|
||||
"name": "@dabh/diagnostics",
|
||||
"version": "2.0.3",
|
||||
"description": "Tools for debugging your node.js modules and event loop",
|
||||
"main": "./node",
|
||||
"browser": "./browser",
|
||||
"scripts": {
|
||||
"test:basic": "mocha --require test/mock.js test/*.test.js",
|
||||
"test:node": "mocha --require test/mock test/node.js",
|
||||
"test:browser": "mocha --require test/mock test/browser.js",
|
||||
"test:runner": "npm run test:basic && npm run test:node && npm run test:browser",
|
||||
"webpack:node:prod": "webpack --mode=production node/index.js -o /dev/null --json | webpack-bundle-size-analyzer",
|
||||
"webpack:node:dev": "webpack --mode=development node/index.js -o /dev/null --json | webpack-bundle-size-analyzer",
|
||||
"webpack:browser:prod": "webpack --mode=production browser/index.js -o /dev/null --json | webpack-bundle-size-analyzer",
|
||||
"webpack:browser:dev": "webpack --mode=development browser/index.js -o /dev/null --json | webpack-bundle-size-analyzer",
|
||||
"test": "nyc --reporter=text --reporter=lcov npm run test:runner"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/3rd-Eden/diagnostics.git"
|
||||
},
|
||||
"keywords": [
|
||||
"debug",
|
||||
"debugger",
|
||||
"debugging",
|
||||
"diagnostic",
|
||||
"diagnostics",
|
||||
"event",
|
||||
"loop",
|
||||
"metrics",
|
||||
"stats"
|
||||
],
|
||||
"author": "Arnout Kazemier",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/3rd-Eden/diagnostics/issues"
|
||||
},
|
||||
"homepage": "https://github.com/3rd-Eden/diagnostics",
|
||||
"devDependencies": {
|
||||
"assume": "2.3.x",
|
||||
"asyncstorageapi": "^1.0.2",
|
||||
"mocha": "9.2.x",
|
||||
"nyc": "^15.1.0",
|
||||
"objstorage": "^1.0.0",
|
||||
"pre-commit": "1.2.x",
|
||||
"require-poisoning": "^2.0.0",
|
||||
"webpack": "4.x",
|
||||
"webpack-bundle-size-analyzer": "^3.0.0",
|
||||
"webpack-cli": "3.x"
|
||||
},
|
||||
"dependencies": {
|
||||
"colorspace": "1.1.x",
|
||||
"enabled": "2.0.x",
|
||||
"kuler": "^2.0.0"
|
||||
},
|
||||
"contributors": [
|
||||
"Martijn Swaagman (https://github.com/swaagie)",
|
||||
"Jarrett Cruger (https://github.com/jcrugzz)",
|
||||
"Sevastos (https://github.com/sevastos)"
|
||||
],
|
||||
"directories": {
|
||||
"test": "test"
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
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
|
||||
@ -0,0 +1,42 @@
|
||||
# Installation
|
||||
> `npm install --save @types/triple-beam`
|
||||
|
||||
# Summary
|
||||
This package contains type definitions for triple-beam (https://github.com/winstonjs/triple-beam).
|
||||
|
||||
# Details
|
||||
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/triple-beam.
|
||||
## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/triple-beam/index.d.ts)
|
||||
````ts
|
||||
// Type definitions for triple-beam 1.3
|
||||
// Project: https://github.com/winstonjs/triple-beam
|
||||
// Definitions by: Daniel Byrne <https://github.com/danwbyrne>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
|
||||
export as namespace TripleBeam;
|
||||
|
||||
export const LEVEL: unique symbol;
|
||||
export const MESSAGE: unique symbol;
|
||||
export const SPLAT: unique symbol;
|
||||
export const configs: Configs;
|
||||
|
||||
export interface Config {
|
||||
readonly levels: { [k: string]: number };
|
||||
readonly colors: { [k: string]: string };
|
||||
}
|
||||
|
||||
export interface Configs {
|
||||
readonly cli: Config;
|
||||
readonly npm: Config;
|
||||
readonly syslog: Config;
|
||||
}
|
||||
|
||||
````
|
||||
|
||||
### Additional Details
|
||||
* Last updated: Tue, 12 Sep 2023 12:34:50 GMT
|
||||
* Dependencies: none
|
||||
* Global values: `TripleBeam`
|
||||
|
||||
# Credits
|
||||
These definitions were written by [Daniel Byrne](https://github.com/danwbyrne).
|
||||
@ -0,0 +1,22 @@
|
||||
// Type definitions for triple-beam 1.3
|
||||
// Project: https://github.com/winstonjs/triple-beam
|
||||
// Definitions by: Daniel Byrne <https://github.com/danwbyrne>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
|
||||
export as namespace TripleBeam;
|
||||
|
||||
export const LEVEL: unique symbol;
|
||||
export const MESSAGE: unique symbol;
|
||||
export const SPLAT: unique symbol;
|
||||
export const configs: Configs;
|
||||
|
||||
export interface Config {
|
||||
readonly levels: { [k: string]: number };
|
||||
readonly colors: { [k: string]: string };
|
||||
}
|
||||
|
||||
export interface Configs {
|
||||
readonly cli: Config;
|
||||
readonly npm: Config;
|
||||
readonly syslog: Config;
|
||||
}
|
||||
@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "@types/triple-beam",
|
||||
"version": "1.3.3",
|
||||
"description": "TypeScript definitions for triple-beam",
|
||||
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/triple-beam",
|
||||
"license": "MIT",
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Daniel Byrne",
|
||||
"url": "https://github.com/danwbyrne",
|
||||
"githubUsername": "danwbyrne"
|
||||
}
|
||||
],
|
||||
"main": "",
|
||||
"types": "index.d.ts",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
|
||||
"directory": "types/triple-beam"
|
||||
},
|
||||
"scripts": {},
|
||||
"dependencies": {},
|
||||
"typesPublisherContentHash": "fcfcae61b31660fd3b3fbd9739d3351c082839a97884d73f3d147c88b1013fc8",
|
||||
"typeScriptVersion": "4.3"
|
||||
}
|
||||
@ -0,0 +1,243 @@
|
||||
1.3.8 / 2022-02-02
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.34
|
||||
- deps: mime-db@~1.51.0
|
||||
* deps: negotiator@0.6.3
|
||||
|
||||
1.3.7 / 2019-04-29
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.6.2
|
||||
- Fix sorting charset, encoding, and language with extra parameters
|
||||
|
||||
1.3.6 / 2019-04-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.24
|
||||
- deps: mime-db@~1.40.0
|
||||
|
||||
1.3.5 / 2018-02-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.18
|
||||
- deps: mime-db@~1.33.0
|
||||
|
||||
1.3.4 / 2017-08-22
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.16
|
||||
- deps: mime-db@~1.29.0
|
||||
|
||||
1.3.3 / 2016-05-02
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.11
|
||||
- deps: mime-db@~1.23.0
|
||||
* deps: negotiator@0.6.1
|
||||
- perf: improve `Accept` parsing speed
|
||||
- perf: improve `Accept-Charset` parsing speed
|
||||
- perf: improve `Accept-Encoding` parsing speed
|
||||
- perf: improve `Accept-Language` parsing speed
|
||||
|
||||
1.3.2 / 2016-03-08
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.10
|
||||
- Fix extension of `application/dash+xml`
|
||||
- Update primary extension for `audio/mp4`
|
||||
- deps: mime-db@~1.22.0
|
||||
|
||||
1.3.1 / 2016-01-19
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.9
|
||||
- deps: mime-db@~1.21.0
|
||||
|
||||
1.3.0 / 2015-09-29
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.7
|
||||
- deps: mime-db@~1.19.0
|
||||
* deps: negotiator@0.6.0
|
||||
- Fix including type extensions in parameters in `Accept` parsing
|
||||
- Fix parsing `Accept` parameters with quoted equals
|
||||
- Fix parsing `Accept` parameters with quoted semicolons
|
||||
- Lazy-load modules from main entry point
|
||||
- perf: delay type concatenation until needed
|
||||
- perf: enable strict mode
|
||||
- perf: hoist regular expressions
|
||||
- perf: remove closures getting spec properties
|
||||
- perf: remove a closure from media type parsing
|
||||
- perf: remove property delete from media type parsing
|
||||
|
||||
1.2.13 / 2015-09-06
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.6
|
||||
- deps: mime-db@~1.18.0
|
||||
|
||||
1.2.12 / 2015-07-30
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.4
|
||||
- deps: mime-db@~1.16.0
|
||||
|
||||
1.2.11 / 2015-07-16
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.3
|
||||
- deps: mime-db@~1.15.0
|
||||
|
||||
1.2.10 / 2015-07-01
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.2
|
||||
- deps: mime-db@~1.14.0
|
||||
|
||||
1.2.9 / 2015-06-08
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.1
|
||||
- perf: fix deopt during mapping
|
||||
|
||||
1.2.8 / 2015-06-07
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.0
|
||||
- deps: mime-db@~1.13.0
|
||||
* perf: avoid argument reassignment & argument slice
|
||||
* perf: avoid negotiator recursive construction
|
||||
* perf: enable strict mode
|
||||
* perf: remove unnecessary bitwise operator
|
||||
|
||||
1.2.7 / 2015-05-10
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.5.3
|
||||
- Fix media type parameter matching to be case-insensitive
|
||||
|
||||
1.2.6 / 2015-05-07
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.11
|
||||
- deps: mime-db@~1.9.1
|
||||
* deps: negotiator@0.5.2
|
||||
- Fix comparing media types with quoted values
|
||||
- Fix splitting media types with quoted commas
|
||||
|
||||
1.2.5 / 2015-03-13
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.10
|
||||
- deps: mime-db@~1.8.0
|
||||
|
||||
1.2.4 / 2015-02-14
|
||||
==================
|
||||
|
||||
* Support Node.js 0.6
|
||||
* deps: mime-types@~2.0.9
|
||||
- deps: mime-db@~1.7.0
|
||||
* deps: negotiator@0.5.1
|
||||
- Fix preference sorting to be stable for long acceptable lists
|
||||
|
||||
1.2.3 / 2015-01-31
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.8
|
||||
- deps: mime-db@~1.6.0
|
||||
|
||||
1.2.2 / 2014-12-30
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.7
|
||||
- deps: mime-db@~1.5.0
|
||||
|
||||
1.2.1 / 2014-12-30
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.5
|
||||
- deps: mime-db@~1.3.1
|
||||
|
||||
1.2.0 / 2014-12-19
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.5.0
|
||||
- Fix list return order when large accepted list
|
||||
- Fix missing identity encoding when q=0 exists
|
||||
- Remove dynamic building of Negotiator class
|
||||
|
||||
1.1.4 / 2014-12-10
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.4
|
||||
- deps: mime-db@~1.3.0
|
||||
|
||||
1.1.3 / 2014-11-09
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.3
|
||||
- deps: mime-db@~1.2.0
|
||||
|
||||
1.1.2 / 2014-10-14
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.9
|
||||
- Fix error when media type has invalid parameter
|
||||
|
||||
1.1.1 / 2014-09-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.2
|
||||
- deps: mime-db@~1.1.0
|
||||
* deps: negotiator@0.4.8
|
||||
- Fix all negotiations to be case-insensitive
|
||||
- Stable sort preferences of same quality according to client order
|
||||
|
||||
1.1.0 / 2014-09-02
|
||||
==================
|
||||
|
||||
* update `mime-types`
|
||||
|
||||
1.0.7 / 2014-07-04
|
||||
==================
|
||||
|
||||
* Fix wrong type returned from `type` when match after unknown extension
|
||||
|
||||
1.0.6 / 2014-06-24
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.7
|
||||
|
||||
1.0.5 / 2014-06-20
|
||||
==================
|
||||
|
||||
* fix crash when unknown extension given
|
||||
|
||||
1.0.4 / 2014-06-19
|
||||
==================
|
||||
|
||||
* use `mime-types`
|
||||
|
||||
1.0.3 / 2014-06-11
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.6
|
||||
- Order by specificity when quality is the same
|
||||
|
||||
1.0.2 / 2014-05-29
|
||||
==================
|
||||
|
||||
* Fix interpretation when header not in request
|
||||
* deps: pin negotiator@0.4.5
|
||||
|
||||
1.0.1 / 2014-01-18
|
||||
==================
|
||||
|
||||
* Identity encoding isn't always acceptable
|
||||
* deps: negotiator@~0.4.0
|
||||
|
||||
1.0.0 / 2013-12-27
|
||||
==================
|
||||
|
||||
* Genesis
|
||||
@ -0,0 +1,23 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
|
||||
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
|
||||
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.
|
||||
@ -0,0 +1,140 @@
|
||||
# accepts
|
||||
|
||||
[![NPM Version][npm-version-image]][npm-url]
|
||||
[![NPM Downloads][npm-downloads-image]][npm-url]
|
||||
[![Node.js Version][node-version-image]][node-version-url]
|
||||
[![Build Status][github-actions-ci-image]][github-actions-ci-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator).
|
||||
Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
|
||||
|
||||
In addition to negotiator, it allows:
|
||||
|
||||
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])`
|
||||
as well as `('text/html', 'application/json')`.
|
||||
- Allows type shorthands such as `json`.
|
||||
- Returns `false` when no types match
|
||||
- Treats non-existent headers as `*`
|
||||
|
||||
## Installation
|
||||
|
||||
This is a [Node.js](https://nodejs.org/en/) module available through the
|
||||
[npm registry](https://www.npmjs.com/). Installation is done using the
|
||||
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
|
||||
|
||||
```sh
|
||||
$ npm install accepts
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
```js
|
||||
var accepts = require('accepts')
|
||||
```
|
||||
|
||||
### accepts(req)
|
||||
|
||||
Create a new `Accepts` object for the given `req`.
|
||||
|
||||
#### .charset(charsets)
|
||||
|
||||
Return the first accepted charset. If nothing in `charsets` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .charsets()
|
||||
|
||||
Return the charsets that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .encoding(encodings)
|
||||
|
||||
Return the first accepted encoding. If nothing in `encodings` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .encodings()
|
||||
|
||||
Return the encodings that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .language(languages)
|
||||
|
||||
Return the first accepted language. If nothing in `languages` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .languages()
|
||||
|
||||
Return the languages that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .type(types)
|
||||
|
||||
Return the first accepted type (and it is returned as the same text as what
|
||||
appears in the `types` array). If nothing in `types` is accepted, then `false`
|
||||
is returned.
|
||||
|
||||
The `types` array can contain full MIME types or file extensions. Any value
|
||||
that is not a full MIME types is passed to `require('mime-types').lookup`.
|
||||
|
||||
#### .types()
|
||||
|
||||
Return the types that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
## Examples
|
||||
|
||||
### Simple type negotiation
|
||||
|
||||
This simple example shows how to use `accepts` to return a different typed
|
||||
respond body based on what the client wants to accept. The server lists it's
|
||||
preferences in order and will get back the best match between the client and
|
||||
server.
|
||||
|
||||
```js
|
||||
var accepts = require('accepts')
|
||||
var http = require('http')
|
||||
|
||||
function app (req, res) {
|
||||
var accept = accepts(req)
|
||||
|
||||
// the order of this list is significant; should be server preferred order
|
||||
switch (accept.type(['json', 'html'])) {
|
||||
case 'json':
|
||||
res.setHeader('Content-Type', 'application/json')
|
||||
res.write('{"hello":"world!"}')
|
||||
break
|
||||
case 'html':
|
||||
res.setHeader('Content-Type', 'text/html')
|
||||
res.write('<b>hello, world!</b>')
|
||||
break
|
||||
default:
|
||||
// the fallback is text/plain, so no need to specify it above
|
||||
res.setHeader('Content-Type', 'text/plain')
|
||||
res.write('hello, world!')
|
||||
break
|
||||
}
|
||||
|
||||
res.end()
|
||||
}
|
||||
|
||||
http.createServer(app).listen(3000)
|
||||
```
|
||||
|
||||
You can test this out with the cURL program:
|
||||
```sh
|
||||
curl -I -H'Accept: text/html' http://localhost:3000/
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master
|
||||
[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master
|
||||
[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci
|
||||
[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml
|
||||
[node-version-image]: https://badgen.net/npm/node/accepts
|
||||
[node-version-url]: https://nodejs.org/en/download
|
||||
[npm-downloads-image]: https://badgen.net/npm/dm/accepts
|
||||
[npm-url]: https://npmjs.org/package/accepts
|
||||
[npm-version-image]: https://badgen.net/npm/v/accepts
|
||||
@ -0,0 +1,238 @@
|
||||
/*!
|
||||
* accepts
|
||||
* Copyright(c) 2014 Jonathan Ong
|
||||
* Copyright(c) 2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var Negotiator = require('negotiator')
|
||||
var mime = require('mime-types')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @public
|
||||
*/
|
||||
|
||||
module.exports = Accepts
|
||||
|
||||
/**
|
||||
* Create a new Accepts object for the given req.
|
||||
*
|
||||
* @param {object} req
|
||||
* @public
|
||||
*/
|
||||
|
||||
function Accepts (req) {
|
||||
if (!(this instanceof Accepts)) {
|
||||
return new Accepts(req)
|
||||
}
|
||||
|
||||
this.headers = req.headers
|
||||
this.negotiator = new Negotiator(req)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given `type(s)` is acceptable, returning
|
||||
* the best match when true, otherwise `undefined`, in which
|
||||
* case you should respond with 406 "Not Acceptable".
|
||||
*
|
||||
* The `type` value may be a single mime type string
|
||||
* such as "application/json", the extension name
|
||||
* such as "json" or an array `["json", "html", "text/plain"]`. When a list
|
||||
* or array is given the _best_ match, if any is returned.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* // Accept: text/html
|
||||
* this.types('html');
|
||||
* // => "html"
|
||||
*
|
||||
* // Accept: text/*, application/json
|
||||
* this.types('html');
|
||||
* // => "html"
|
||||
* this.types('text/html');
|
||||
* // => "text/html"
|
||||
* this.types('json', 'text');
|
||||
* // => "json"
|
||||
* this.types('application/json');
|
||||
* // => "application/json"
|
||||
*
|
||||
* // Accept: text/*, application/json
|
||||
* this.types('image/png');
|
||||
* this.types('png');
|
||||
* // => undefined
|
||||
*
|
||||
* // Accept: text/*;q=.5, application/json
|
||||
* this.types(['html', 'json']);
|
||||
* this.types('html', 'json');
|
||||
* // => "json"
|
||||
*
|
||||
* @param {String|Array} types...
|
||||
* @return {String|Array|Boolean}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.type =
|
||||
Accepts.prototype.types = function (types_) {
|
||||
var types = types_
|
||||
|
||||
// support flattened arguments
|
||||
if (types && !Array.isArray(types)) {
|
||||
types = new Array(arguments.length)
|
||||
for (var i = 0; i < types.length; i++) {
|
||||
types[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no types, return all requested types
|
||||
if (!types || types.length === 0) {
|
||||
return this.negotiator.mediaTypes()
|
||||
}
|
||||
|
||||
// no accept header, return first given type
|
||||
if (!this.headers.accept) {
|
||||
return types[0]
|
||||
}
|
||||
|
||||
var mimes = types.map(extToMime)
|
||||
var accepts = this.negotiator.mediaTypes(mimes.filter(validMime))
|
||||
var first = accepts[0]
|
||||
|
||||
return first
|
||||
? types[mimes.indexOf(first)]
|
||||
: false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted encodings or best fit based on `encodings`.
|
||||
*
|
||||
* Given `Accept-Encoding: gzip, deflate`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['gzip', 'deflate']
|
||||
*
|
||||
* @param {String|Array} encodings...
|
||||
* @return {String|Array}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.encoding =
|
||||
Accepts.prototype.encodings = function (encodings_) {
|
||||
var encodings = encodings_
|
||||
|
||||
// support flattened arguments
|
||||
if (encodings && !Array.isArray(encodings)) {
|
||||
encodings = new Array(arguments.length)
|
||||
for (var i = 0; i < encodings.length; i++) {
|
||||
encodings[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no encodings, return all requested encodings
|
||||
if (!encodings || encodings.length === 0) {
|
||||
return this.negotiator.encodings()
|
||||
}
|
||||
|
||||
return this.negotiator.encodings(encodings)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted charsets or best fit based on `charsets`.
|
||||
*
|
||||
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['utf-8', 'utf-7', 'iso-8859-1']
|
||||
*
|
||||
* @param {String|Array} charsets...
|
||||
* @return {String|Array}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.charset =
|
||||
Accepts.prototype.charsets = function (charsets_) {
|
||||
var charsets = charsets_
|
||||
|
||||
// support flattened arguments
|
||||
if (charsets && !Array.isArray(charsets)) {
|
||||
charsets = new Array(arguments.length)
|
||||
for (var i = 0; i < charsets.length; i++) {
|
||||
charsets[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no charsets, return all requested charsets
|
||||
if (!charsets || charsets.length === 0) {
|
||||
return this.negotiator.charsets()
|
||||
}
|
||||
|
||||
return this.negotiator.charsets(charsets)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted languages or best fit based on `langs`.
|
||||
*
|
||||
* Given `Accept-Language: en;q=0.8, es, pt`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['es', 'pt', 'en']
|
||||
*
|
||||
* @param {String|Array} langs...
|
||||
* @return {Array|String}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.lang =
|
||||
Accepts.prototype.langs =
|
||||
Accepts.prototype.language =
|
||||
Accepts.prototype.languages = function (languages_) {
|
||||
var languages = languages_
|
||||
|
||||
// support flattened arguments
|
||||
if (languages && !Array.isArray(languages)) {
|
||||
languages = new Array(arguments.length)
|
||||
for (var i = 0; i < languages.length; i++) {
|
||||
languages[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no languages, return all requested languages
|
||||
if (!languages || languages.length === 0) {
|
||||
return this.negotiator.languages()
|
||||
}
|
||||
|
||||
return this.negotiator.languages(languages)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert extnames to mime.
|
||||
*
|
||||
* @param {String} type
|
||||
* @return {String}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function extToMime (type) {
|
||||
return type.indexOf('/') === -1
|
||||
? mime.lookup(type)
|
||||
: type
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if mime is valid.
|
||||
*
|
||||
* @param {String} type
|
||||
* @return {String}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function validMime (type) {
|
||||
return typeof type === 'string'
|
||||
}
|
||||
@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "accepts",
|
||||
"description": "Higher-level content negotiation",
|
||||
"version": "1.3.8",
|
||||
"contributors": [
|
||||
"Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": "jshttp/accepts",
|
||||
"dependencies": {
|
||||
"mime-types": "~2.1.34",
|
||||
"negotiator": "0.6.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"deep-equal": "1.0.1",
|
||||
"eslint": "7.32.0",
|
||||
"eslint-config-standard": "14.1.1",
|
||||
"eslint-plugin-import": "2.25.4",
|
||||
"eslint-plugin-markdown": "2.2.1",
|
||||
"eslint-plugin-node": "11.1.0",
|
||||
"eslint-plugin-promise": "4.3.1",
|
||||
"eslint-plugin-standard": "4.1.0",
|
||||
"mocha": "9.2.0",
|
||||
"nyc": "15.1.0"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"HISTORY.md",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --reporter spec --check-leaks --bail test/",
|
||||
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test"
|
||||
},
|
||||
"keywords": [
|
||||
"content",
|
||||
"negotiation",
|
||||
"accept",
|
||||
"accepts"
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
Copyright (c) 2014 Forbes Lindesay
|
||||
|
||||
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.
|
||||
@ -0,0 +1,76 @@
|
||||
# acorn-globals
|
||||
|
||||
Detect global variables in JavaScript using acorn
|
||||
|
||||
[](https://travis-ci.org/ForbesLindesay/acorn-globals)
|
||||
[](https://david-dm.org/ForbesLindesay/acorn-globals)
|
||||
[](https://www.npmjs.org/package/acorn-globals)
|
||||
|
||||
## Installation
|
||||
|
||||
npm install acorn-globals
|
||||
|
||||
## Usage
|
||||
|
||||
detect.js
|
||||
|
||||
```js
|
||||
var fs = require('fs');
|
||||
var detect = require('acorn-globals');
|
||||
|
||||
var src = fs.readFileSync(__dirname + '/input.js', 'utf8');
|
||||
|
||||
var scope = detect(src);
|
||||
console.dir(scope);
|
||||
```
|
||||
|
||||
input.js
|
||||
|
||||
```js
|
||||
var x = 5;
|
||||
var y = 3, z = 2;
|
||||
|
||||
w.foo();
|
||||
w = 2;
|
||||
|
||||
RAWR=444;
|
||||
RAWR.foo();
|
||||
|
||||
BLARG=3;
|
||||
|
||||
foo(function () {
|
||||
var BAR = 3;
|
||||
process.nextTick(function (ZZZZZZZZZZZZ) {
|
||||
console.log('beep boop');
|
||||
var xyz = 4;
|
||||
x += 10;
|
||||
x.zzzzzz;
|
||||
ZZZ=6;
|
||||
});
|
||||
function doom () {
|
||||
}
|
||||
ZZZ.foo();
|
||||
|
||||
});
|
||||
|
||||
console.log(xyz);
|
||||
```
|
||||
|
||||
output:
|
||||
|
||||
```
|
||||
$ node example/detect.js
|
||||
[ { name: 'BLARG', nodes: [ [Object] ] },
|
||||
{ name: 'RAWR', nodes: [ [Object], [Object] ] },
|
||||
{ name: 'ZZZ', nodes: [ [Object], [Object] ] },
|
||||
{ name: 'console', nodes: [ [Object], [Object] ] },
|
||||
{ name: 'foo', nodes: [ [Object] ] },
|
||||
{ name: 'process', nodes: [ [Object] ] },
|
||||
{ name: 'w', nodes: [ [Object], [Object] ] },
|
||||
{ name: 'xyz', nodes: [ [Object] ] } ]
|
||||
```
|
||||
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@ -0,0 +1,180 @@
|
||||
'use strict';
|
||||
|
||||
var acorn = require('acorn');
|
||||
var walk = require('acorn/dist/walk');
|
||||
|
||||
function isScope(node) {
|
||||
return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration' || node.type === 'ArrowFunctionExpression' || node.type === 'Program';
|
||||
}
|
||||
function isBlockScope(node) {
|
||||
return node.type === 'BlockStatement' || isScope(node);
|
||||
}
|
||||
|
||||
function declaresArguments(node) {
|
||||
return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration';
|
||||
}
|
||||
|
||||
function declaresThis(node) {
|
||||
return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration';
|
||||
}
|
||||
|
||||
function reallyParse(source) {
|
||||
try {
|
||||
return acorn.parse(source, {
|
||||
ecmaVersion: 6,
|
||||
allowReturnOutsideFunction: true,
|
||||
allowImportExportEverywhere: true,
|
||||
allowHashBang: true
|
||||
});
|
||||
} catch (ex) {
|
||||
return acorn.parse(source, {
|
||||
ecmaVersion: 5,
|
||||
allowReturnOutsideFunction: true,
|
||||
allowImportExportEverywhere: true,
|
||||
allowHashBang: true
|
||||
});
|
||||
}
|
||||
}
|
||||
module.exports = findGlobals;
|
||||
module.exports.parse = reallyParse;
|
||||
function findGlobals(source) {
|
||||
var globals = [];
|
||||
var ast;
|
||||
// istanbul ignore else
|
||||
if (typeof source === 'string') {
|
||||
ast = reallyParse(source);
|
||||
} else {
|
||||
ast = source;
|
||||
}
|
||||
// istanbul ignore if
|
||||
if (!(ast && typeof ast === 'object' && ast.type === 'Program')) {
|
||||
throw new TypeError('Source must be either a string of JavaScript or an acorn AST');
|
||||
}
|
||||
var declareFunction = function (node) {
|
||||
var fn = node;
|
||||
fn.locals = fn.locals || {};
|
||||
node.params.forEach(function (node) {
|
||||
declarePattern(node, fn);
|
||||
});
|
||||
if (node.id) {
|
||||
fn.locals[node.id.name] = true;
|
||||
}
|
||||
}
|
||||
var declarePattern = function (node, parent) {
|
||||
switch (node.type) {
|
||||
case 'Identifier':
|
||||
parent.locals[node.name] = true;
|
||||
break;
|
||||
case 'ObjectPattern':
|
||||
node.properties.forEach(function (node) {
|
||||
declarePattern(node.value, parent);
|
||||
});
|
||||
break;
|
||||
case 'ArrayPattern':
|
||||
node.elements.forEach(function (node) {
|
||||
if (node) declarePattern(node, parent);
|
||||
});
|
||||
break;
|
||||
case 'RestElement':
|
||||
declarePattern(node.argument, parent);
|
||||
break;
|
||||
case 'AssignmentPattern':
|
||||
declarePattern(node.left, parent);
|
||||
break;
|
||||
// istanbul ignore next
|
||||
default:
|
||||
throw new Error('Unrecognized pattern type: ' + node.type);
|
||||
}
|
||||
}
|
||||
var declareModuleSpecifier = function (node, parents) {
|
||||
ast.locals = ast.locals || {};
|
||||
ast.locals[node.local.name] = true;
|
||||
}
|
||||
walk.ancestor(ast, {
|
||||
'VariableDeclaration': function (node, parents) {
|
||||
var parent = null;
|
||||
for (var i = parents.length - 1; i >= 0 && parent === null; i--) {
|
||||
if (node.kind === 'var' ? isScope(parents[i]) : isBlockScope(parents[i])) {
|
||||
parent = parents[i];
|
||||
}
|
||||
}
|
||||
parent.locals = parent.locals || {};
|
||||
node.declarations.forEach(function (declaration) {
|
||||
declarePattern(declaration.id, parent);
|
||||
});
|
||||
},
|
||||
'FunctionDeclaration': function (node, parents) {
|
||||
var parent = null;
|
||||
for (var i = parents.length - 2; i >= 0 && parent === null; i--) {
|
||||
if (isScope(parents[i])) {
|
||||
parent = parents[i];
|
||||
}
|
||||
}
|
||||
parent.locals = parent.locals || {};
|
||||
parent.locals[node.id.name] = true;
|
||||
declareFunction(node);
|
||||
},
|
||||
'Function': declareFunction,
|
||||
'ClassDeclaration': function (node, parents) {
|
||||
var parent = null;
|
||||
for (var i = parents.length - 2; i >= 0 && parent === null; i--) {
|
||||
if (isScope(parents[i])) {
|
||||
parent = parents[i];
|
||||
}
|
||||
}
|
||||
parent.locals = parent.locals || {};
|
||||
parent.locals[node.id.name] = true;
|
||||
},
|
||||
'TryStatement': function (node) {
|
||||
if (node.handler === null) return;
|
||||
node.handler.body.locals = node.handler.body.locals || {};
|
||||
node.handler.body.locals[node.handler.param.name] = true;
|
||||
},
|
||||
'ImportDefaultSpecifier': declareModuleSpecifier,
|
||||
'ImportSpecifier': declareModuleSpecifier,
|
||||
'ImportNamespaceSpecifier': declareModuleSpecifier
|
||||
});
|
||||
function identifier(node, parents) {
|
||||
var name = node.name;
|
||||
if (name === 'undefined') return;
|
||||
for (var i = 0; i < parents.length; i++) {
|
||||
if (name === 'arguments' && declaresArguments(parents[i])) {
|
||||
return;
|
||||
}
|
||||
if (parents[i].locals && name in parents[i].locals) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (
|
||||
parents[parents.length - 2] &&
|
||||
parents[parents.length - 2].type === 'TryStatement' &&
|
||||
parents[parents.length - 2].handler &&
|
||||
node === parents[parents.length - 2].handler.param
|
||||
) {
|
||||
return;
|
||||
}
|
||||
node.parents = parents;
|
||||
globals.push(node);
|
||||
}
|
||||
walk.ancestor(ast, {
|
||||
'VariablePattern': identifier,
|
||||
'Identifier': identifier,
|
||||
'ThisExpression': function (node, parents) {
|
||||
for (var i = 0; i < parents.length; i++) {
|
||||
if (declaresThis(parents[i])) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
node.parents = parents;
|
||||
globals.push(node);
|
||||
}
|
||||
});
|
||||
var groupedGlobals = {};
|
||||
globals.forEach(function (node) {
|
||||
groupedGlobals[node.name] = (groupedGlobals[node.name] || []);
|
||||
groupedGlobals[node.name].push(node);
|
||||
});
|
||||
return Object.keys(groupedGlobals).sort().map(function (name) {
|
||||
return {name: name, nodes: groupedGlobals[name]};
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "acorn-globals",
|
||||
"version": "1.0.9",
|
||||
"description": "Detect global variables in JavaScript using acorn",
|
||||
"keywords": [
|
||||
"ast",
|
||||
"variable",
|
||||
"name",
|
||||
"lexical",
|
||||
"scope",
|
||||
"local",
|
||||
"global",
|
||||
"implicit"
|
||||
],
|
||||
"files": [
|
||||
"index.js",
|
||||
"LICENSE"
|
||||
],
|
||||
"dependencies": {
|
||||
"acorn": "^2.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"testit": "^2.0.2"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node test"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/ForbesLindesay/acorn-globals.git"
|
||||
},
|
||||
"author": "ForbesLindesay",
|
||||
"license": "MIT"
|
||||
}
|
||||
@ -0,0 +1,7 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
@ -0,0 +1 @@
|
||||
* text eol=lf
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue