chrisheo

Refactor folder location and add node.js files

Showing 348 changed files with 407 additions and 4346 deletions
1 +module.exports = function(app){
2 + var request = require("request");
3 + var urlenconde = require('urlencode');
4 + var apikey = "RGAPI-539b7900-4377-44be-80ea-f0a88bb9b641"//api
5 + var profileIconId; //아이콘 번호
6 + var revisionDate; //수정날짜
7 + var id; //소환사ID
8 + var accountId; //계정Id
9 + var name; //소환사 이름
10 + var summonerLevel; //소환사
11 + var rotation_champ = new Array();
12 + app.get('/', function(req, res) {
13 + res.render('main', { title: 'R U TROLL?' });
14 + });
15 + app.get('/search/:username/', function(req, res, next){
16 + //롤 api url
17 + name = req.params.username;
18 + var nameUrl = "https://kr.api.riotgames.com/lol/summoner/v4/summoners/by-name/" + urlenconde(name)+"?api_key="+ apikey;
19 + request(nameUrl,function(error,response,body){
20 + // 요청에 대한 응답이 성공적으로 왔는지 검사.
21 + // status code가 200이 아니면 오류가 있었던 것으로 간주하고 함수 종료.
22 + console.log('response code ', response.statusCode);
23 + if (response.statusCode != 200) {
24 + console.log('Error with response code22 ', response.statusCode);
25 + res.end();
26 + return;
27 + }
28 + var info_summoner_json = JSON.parse(body);
29 + accountId = info_summoner_json["accountId"];
30 + id = info_summoner_json["id"];
31 + summoner = info_summoner_json["name"];
32 + profileIconId = info_summoner_json["profileIconId"];
33 + summonerLevel = info_summoner_json["summonerLevel"];
34 + revisionDate = info_summoner_json["revisionDate"];
35 + var champUrl = "https://kr.api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/" + urlenconde(id) + "?api_key=" + apikey;
36 + request(champUrl,function(error,response,body){
37 + var info_champ_json = JSON.parse(body);
38 + var champ_point = new Array();
39 + var champ_id = new Array();
40 + var champ_name = new Array();
41 + var rotation_name = new Array();
42 + var champ_pic = new Array();
43 + var rotation_pic =new Array();
44 + var champions_length = Object.keys(info_champ_json).length;
45 + //console.log("\n\ninfo_champ_json\n\n", info_champ_json);
46 + // status code가 200이 아니면 종료.
47 + if (info_champ_json["status"] != undefined) {
48 + if (info_champ_json["status"]["status_code"] != 200) {
49 + console.log('Error with response code11 ', info_champ_json["status"]["status_code"]);
50 + res.end();
51 + return;
52 + }
53 + }
54 + for(var i=0; i < champions_length; i++){
55 + champ_point[i] = (info_champ_json[i]["championPoints"]);
56 + champ_id[i] = info_champ_json[i]["championId"];
57 + }
58 + var rotationUrl = "https://kr.api.riotgames.com/lol/platform/v3/champion-rotations?api_key="+apikey;
59 + request(rotationUrl,function(error,response,body){
60 + var info_rotation = JSON.parse(body);
61 + var keys = Object.keys(info_rotation);
62 + for(var k =0; k < info_rotation[keys[0]].length;k++)
63 + {
64 + rotation_champ[k] =info_rotation[keys[0]][k]
65 + console.log("rotation_champ:"+rotation_champ[k]);
66 + console.log("로테길이:"+rotation_champ.length);
67 + }
68 + var staticUrl = "http://ddragon.leagueoflegends.com/cdn/9.23.1/data/en_US/champion.json";
69 + request(staticUrl,function(error,response,body){
70 + var info_static_champ_json = JSON.parse(body);
71 + var champion = info_static_champ_json["data"];
72 + for(var i=0; i < champ_id.length; i++){
73 + for(js in champion){
74 + for(j in champion[js]){
75 + if(champion[js]["key"] == champ_id[i]){
76 + champ_name[i] = champion[js]["id"];
77 + champ_pic[i] = "http://ddragon.leagueoflegends.com/cdn/9.23.1/img/champion/"+champ_name[i]+".png";
78 + }
79 + }
80 + }
81 + }
82 + for(var i=0; i < champ_id.length; i++){
83 + for(js in champion){
84 + for(j in champion[js]){
85 + if(champion[js]["key"] == rotation_champ[i]){
86 + rotation_name[i] = champion[js]["id"];
87 + rotation_pic[i] = "http://ddragon.leagueoflegends.com/cdn/9.23.1/img/champion/"+rotation_name[i]+".png";
88 + }
89 + }
90 + }
91 + }
92 + console.log("챔프길이:"+champ_pic.length);
93 + var userLeagueUrl = "https://kr.api.riotgames.com/lol/league/v4/entries/by-summoner/"+ urlenconde(id)+"?api_key=" + apikey;
94 + request(userLeagueUrl,function(error,response,body){
95 + var info_user_league_json = JSON.parse(body);
96 + //console.log("userLeagueUrl:", userLeagueUrl);
97 + if(info_user_league_json[0] != null){
98 + var leagueId = info_user_league_json[0]["leagueId"];
99 + var wins = info_user_league_json[0]["wins"];
100 + var losses = info_user_league_json[0]["losses"];
101 + var leagueName = info_user_league_json[0]["leagueName"]
102 + var tier = info_user_league_json[0]["tier"];
103 + var rank = info_user_league_json[0]["rank"];
104 + var leaguePoints = info_user_league_json[0]["leaguePoints"];
105 + var img_tier;
106 + if(tier == "MASTER"){
107 + img_tier = "https://i.imgur.com/nvQjonh.png";
108 + }else if(tier == "CHALLENGER"){
109 + img_tier = "https://i.imgur.com/sbK1Edj.png";
110 + }else if(tier == "DIAMOND"){
111 + img_tier = "https://i.imgur.com/5VBu8PF.png"
112 + }else if(tier == "PLATINUM"){
113 + img_tier = "https://i.imgur.com/Eqi6858.png"
114 + }else if(tier == "GRANDMASTER"){
115 + img_tier = "https://i.imgur.com/mcEhz1o.png"
116 + }else if(tier == "GOLD"){
117 + img_tier = "https://i.imgur.com/Ec4hPuO.png"
118 + }else if(tier == "SILVER"){
119 + img_tier = "https://i.imgur.com/GKnPu7s.png"
120 + }else if(tier == "BRONZE"){
121 + img_tier ="https://i.imgur.com/TPZVXIr.png"
122 + }else{
123 + img_tier = "https://i.imgur.com/kcdoC4r.png"
124 + }
125 + }
126 + champ_name[champ_name.length] = "total";
127 + var temp_id;
128 + var temp_name;
129 + var temp_point;
130 + var temp_pic;
131 + for(var i=0; i < champ_id.length-1; i++){
132 + for(var j=i+1;j <champ_id.length-1; j++)
133 + if(champ_point[i] > champ_point[j]){
134 + temp_id = champ_id[i];
135 + temp_name = champ_name[i];
136 + temp_point = champ_point[i];
137 + temp_pic = champ_pic[i];
138 + champ_id[i] = champ_id[j]
139 + champ_name[i] = champ_name[j];
140 + champ_point[i] = champ_point[j];
141 + champ_pic[i] = champ_pic[j];
142 + champ_id[j] = temp_id
143 + champ_name[j] = temp_name;
144 + champ_point[j] = temp_point;
145 + champ_pic[j] = temp_pic;
146 + }
147 + }
148 + const defaultMMR = [
149 + {"mmr" : 900, "tier" : "iron", "rank": 4},
150 + {"mmr" : 950, "tier" : "iron", "rank": 3},
151 + {"mmr" : 1000, "tier" : "iron", "rank": 2},
152 + {"mmr" : 1050, "tier" : "iron", "rank": 1},
153 + { "mmr" : 1100, "tier" : "bronze", "rank": 4 },
154 + { "mmr" : 1150, "tier" : "bronze", "rank": 3 },
155 + { "mmr" : 1200, "tier" : "bronze", "rank": 2 },
156 + { "mmr" : 1250, "tier" : "bronze", "rank": 1 },
157 + { "mmr" : 1300, "tier" : "silver", "rank": 4 },
158 + { "mmr" : 1350, "tier" : "silver", "rank": 3 },
159 + { "mmr" : 1400, "tier" : "silver", "rank": 2 },
160 + { "mmr" : 1450, "tier" : "silver", "rank": 1 },
161 + { "mmr" : 1500, "tier" : "gold", "rank": 4 },
162 + { "mmr" : 1550, "tier" : "gold", "rank": 3 },
163 + { "mmr" : 1600, "tier" : "gold", "rank": 2 },
164 + { "mmr" : 1650, "tier" : "gold", "rank": 1 },
165 + { "mmr" : 1700, "tier" : "platinum", "rank": 4 },
166 + { "mmr" : 1750, "tier" : "platinum", "rank": 3 },
167 + { "mmr" : 1800, "tier" : "platinum", "rank": 2 },
168 + { "mmr" : 1850, "tier" : "platinum", "rank": 1 },
169 + { "mmr" : 1900, "tier" : "diamond", "rank": 4 },
170 + { "mmr" : 1950, "tier" : "diamond", "rank": 3 },
171 + { "mmr" : 2000, "tier" : "diamond", "rank": 2 },
172 + { "mmr" : 2050, "tier" : "diamond", "rank": 1 },
173 + { "mmr" : 2100, "tier" : "master", "rank": 1 },
174 + { "mmr" : 2700, "tier" : "challenger", "rank": 1 },
175 + ]
176 + res.render('index', { title: req.params.username ,
177 + c_id: champ_id,
178 + c_name: champ_name,
179 + c_point: champ_point,
180 + c_pic: champ_pic,
181 + c_rotation : rotation_pic,
182 + c_summoner: summoner,
183 + c_wins: wins,
184 + c_losses: losses,
185 + c_tier: tier,
186 + c_imgtier: img_tier,
187 + c_rank: rank,
188 + c_leaguePoint: leaguePoints
189 + });
190 + });
191 + });
192 + });
193 + });
194 + });
195 + });
196 + };
...\ No newline at end of file ...\ No newline at end of file
1 +var express = require('express');
2 +var app = express();
3 +var router = require('../router/Test')(app);
4 +var bodyParser = require('body-parser');
5 +app.set('views', __dirname + '/views');
6 +app.set('view engine', 'ejs');
7 +app.engine('html', require('ejs').renderFile);
8 +var server = app.listen(3000, function(){
9 + console.log('good');
10 +});
11 +app.use(express.static('public'));
...\ No newline at end of file ...\ No newline at end of file
1 +module.exports = function(app){
2 + var request = require("request");
3 + var urlenconde = require('urlencode');
4 + var apikey = "RGAPI-df870784-f399-4104-bfbb-1b209aeb597f"//api
5 + var profileIconId; //아이콘 번호
6 + var revisionDate; //수정날짜
7 + var id; //소환사ID
8 + var accountId; //계정Id
9 + var name; //소환사 이름
10 + var summonerLevel; //소환사 레벨
11 + var startIndex;
12 + var endIndex;
13 + var totalGames;
14 + var matches; //경기정보
15 + app.get('/', function(req, res) {
16 + res.render('main', { title: 'R U TROLL?' });
17 + });
18 + app.get('/search/:username/', function(req, res){
19 + //롤 api url
20 + name = req.params.username;
21 + var nameUrl = "https://kr.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + urlenconde(name)+"?api_key="+ apikey;
22 + request(nameUrl,function(error,response,body){
23 + var info_summoner_json = JSON.parse(body);
24 + accountId = info_summoner_json["accountId"];
25 + id = info_summoner_json["id"];
26 + summoner = info_summoner_json["name"];
27 + profileIconId = info_summoner_json["profileIconId"];
28 + summonerLevel = info_summoner_json["summonerLevel"];
29 + revisionDate = info_summoner_json["revisionDate"];
30 + var rankedUrl = "https://kr.api.pvp.net/api/lol/kr/v2.5/league/by-summoner/"+ urlenconde(id)+ "?api_key=" + apikey;
31 + var champUrl = "https://kr.api.pvp.net/api/lol/kr/v1.3/stats/by-summoner/" + urlenconde(id) + "/ranked?api_key=" + apikey;
32 + request(champUrl,function(error,response,body){
33 + var info_champ_json = JSON.parse(body);
34 + var champions = info_champ_json["champions"];
35 + var champ_point = new Array();
36 + var champ_id = new Array();
37 + var champ_name = new Array();
38 + var champ_pic = new Array();
39 + var champions_length = Object.keys(champions).length;
40 + for(var i=0; i < champions_length; i++){
41 + champ_point[i] = (champions[i]["stats"]["totalSessionsWon"]/champions[i]["stats"]["totalSessionsPlayed"]*200)
42 + + ((champions[i]["stats"]["totalAssists"]+champions[i]["stats"]["totalChampionKills"])/champions[i]["stats"]["totalDeathsPerSession"]*100)
43 + + (champions[i]["stats"]["totalSessionsPlayed"]*3);
44 + champ_id[i] = champions[i]["id"];
45 + }
46 + var staticUrl = "https://global.api.pvp.net/api/lol/static-data/kr/v1.2/champion/?api_key=" + apikey;
47 + request(staticUrl,function(error,response,body){
48 + var info_static_champ_json = JSON.parse(body);
49 + var champion = info_static_champ_json["data"];
50 + for(var i=0; i < champ_id.length; i++){
51 + for(js in champion){
52 + for(j in champion[js]){
53 + if(champion[js]["id"] == champ_id[i]){
54 + champ_name[i] = champion[js]["key"];
55 + champ_pic[i] = "https://opgg-static.akamaized.net/images/lol/champion/"+champ_name[i]+".png?image=c_scale,w_46";
56 + }
57 + }
58 + }
59 + }
60 + champ_name[champ_name.length] = "total";
61 + var temp_id;
62 + var temp_name;
63 + var temp_point;
64 + var temp_pic;
65 + for(var i=0; i < champ_id.length-1; i++){
66 + for(var j=i+1;j <champ_id.length-1; j++)
67 + if(champ_point[i] > champ_point[j]){
68 + temp_id = champ_id[i];
69 + temp_name = champ_name[i];
70 + temp_point = champ_point[i];
71 + temp_pic = champ_pic[i];
72 + champ_id[i] = champ_id[j]
73 + champ_name[i] = champ_name[j];
74 + champ_point[i] = champ_point[j];
75 + champ_pic[i] = champ_pic[j];
76 + champ_id[j] = temp_id
77 + champ_name[j] = temp_name;
78 + champ_point[j] = temp_point;
79 + champ_pic[j] = temp_pic;
80 + }
81 + }
82 + res.render('index', { title: req.params.username ,
83 + c_id: champ_id,
84 + c_name: champ_name,
85 + c_point: champ_point,
86 + c_pic: champ_pic,
87 + c_summoner: summoner
88 + });
89 + });
90 + });
91 + });
92 + });
93 + };
...\ No newline at end of file ...\ No newline at end of file
1 +.App {
2 + text-align: center;
3 +}
4 +
5 +.App-logo {
6 + height: 40vmin;
7 + pointer-events: none;
8 +}
9 +
10 +@media (prefers-reduced-motion: no-preference) {
11 + .App-logo {
12 + animation: App-logo-spin infinite 20s linear;
13 + }
14 +}
15 +
16 +.App-header {
17 + background-color: #282c34;
18 + min-height: 100vh;
19 + display: flex;
20 + flex-direction: column;
21 + align-items: center;
22 + justify-content: center;
23 + font-size: calc(10px + 2vmin);
24 + color: white;
25 +}
26 +
27 +.App-link {
28 + color: #61dafb;
29 +}
30 +
31 +@keyframes App-logo-spin {
32 + from {
33 + transform: rotate(0deg);
34 + }
35 + to {
36 + transform: rotate(360deg);
37 + }
38 +}
1 +import logo from './logo.svg';
2 +import './App.css';
3 +
4 +function App() {
5 + return (
6 + <div className="App">
7 + <header className="App-header">
8 + <img src={logo} className="App-logo" alt="logo" />
9 + <p>
10 + Edit <code>src/App.js</code> and save to reload.
11 + </p>
12 + <a
13 + className="App-link"
14 + href="https://reactjs.org"
15 + target="_blank"
16 + rel="noopener noreferrer"
17 + >
18 + Learn React
19 + </a>
20 + </header>
21 + </div>
22 + );
23 +}
24 +
25 +export default App;
1 +body {
2 + margin: 0;
3 + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 + 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 + sans-serif;
6 + -webkit-font-smoothing: antialiased;
7 + -moz-osx-font-smoothing: grayscale;
8 +}
9 +
10 +code {
11 + font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 + monospace;
13 +}
1 +import React from 'react';
2 +import ReactDOM from 'react-dom/client';
3 +import './index.css';
4 +import App from './App';
5 +import reportWebVitals from './reportWebVitals';
6 +
7 +const root = ReactDOM.createRoot(document.getElementById('root'));
8 +root.render(
9 + <React.StrictMode>
10 + <App />
11 + </React.StrictMode>
12 +);
13 +
14 +// If you want to start measuring performance in your app, pass a function
15 +// to log results (for example: reportWebVitals(console.log))
16 +// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
17 +reportWebVitals();
1 +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>
...\ No newline at end of file ...\ No newline at end of file
1 +const reportWebVitals = onPerfEntry => {
2 + if (onPerfEntry && onPerfEntry instanceof Function) {
3 + import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
4 + getCLS(onPerfEntry);
5 + getFID(onPerfEntry);
6 + getFCP(onPerfEntry);
7 + getLCP(onPerfEntry);
8 + getTTFB(onPerfEntry);
9 + });
10 + }
11 +};
12 +
13 +export default reportWebVitals;
1 -#!/bin/sh
2 -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
3 -
4 -case `uname` in
5 - *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
6 -esac
7 -
8 -if [ -x "$basedir/node" ]; then
9 - exec "$basedir/node" "$basedir/../sshpk/bin/sshpk-conv" "$@"
10 -else
11 - exec node "$basedir/../sshpk/bin/sshpk-conv" "$@"
12 -fi
1 -@ECHO off
2 -GOTO start
3 -:find_dp0
4 -SET dp0=%~dp0
5 -EXIT /b
6 -:start
7 -SETLOCAL
8 -CALL :find_dp0
9 -
10 -IF EXIST "%dp0%\node.exe" (
11 - SET "_prog=%dp0%\node.exe"
12 -) ELSE (
13 - SET "_prog=node"
14 - SET PATHEXT=%PATHEXT:;.JS;=;%
15 -)
16 -
17 -endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\sshpk\bin\sshpk-conv" %*
1 -#!/usr/bin/env pwsh
2 -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
3 -
4 -$exe=""
5 -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
6 - # Fix case when both the Windows and Linux builds of Node
7 - # are installed in the same directory
8 - $exe=".exe"
9 -}
10 -$ret=0
11 -if (Test-Path "$basedir/node$exe") {
12 - # Support pipeline input
13 - if ($MyInvocation.ExpectingInput) {
14 - $input | & "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-conv" $args
15 - } else {
16 - & "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-conv" $args
17 - }
18 - $ret=$LASTEXITCODE
19 -} else {
20 - # Support pipeline input
21 - if ($MyInvocation.ExpectingInput) {
22 - $input | & "node$exe" "$basedir/../sshpk/bin/sshpk-conv" $args
23 - } else {
24 - & "node$exe" "$basedir/../sshpk/bin/sshpk-conv" $args
25 - }
26 - $ret=$LASTEXITCODE
27 -}
28 -exit $ret
1 -#!/bin/sh
2 -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
3 -
4 -case `uname` in
5 - *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
6 -esac
7 -
8 -if [ -x "$basedir/node" ]; then
9 - exec "$basedir/node" "$basedir/../sshpk/bin/sshpk-sign" "$@"
10 -else
11 - exec node "$basedir/../sshpk/bin/sshpk-sign" "$@"
12 -fi
1 -@ECHO off
2 -GOTO start
3 -:find_dp0
4 -SET dp0=%~dp0
5 -EXIT /b
6 -:start
7 -SETLOCAL
8 -CALL :find_dp0
9 -
10 -IF EXIST "%dp0%\node.exe" (
11 - SET "_prog=%dp0%\node.exe"
12 -) ELSE (
13 - SET "_prog=node"
14 - SET PATHEXT=%PATHEXT:;.JS;=;%
15 -)
16 -
17 -endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\sshpk\bin\sshpk-sign" %*
1 -#!/usr/bin/env pwsh
2 -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
3 -
4 -$exe=""
5 -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
6 - # Fix case when both the Windows and Linux builds of Node
7 - # are installed in the same directory
8 - $exe=".exe"
9 -}
10 -$ret=0
11 -if (Test-Path "$basedir/node$exe") {
12 - # Support pipeline input
13 - if ($MyInvocation.ExpectingInput) {
14 - $input | & "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-sign" $args
15 - } else {
16 - & "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-sign" $args
17 - }
18 - $ret=$LASTEXITCODE
19 -} else {
20 - # Support pipeline input
21 - if ($MyInvocation.ExpectingInput) {
22 - $input | & "node$exe" "$basedir/../sshpk/bin/sshpk-sign" $args
23 - } else {
24 - & "node$exe" "$basedir/../sshpk/bin/sshpk-sign" $args
25 - }
26 - $ret=$LASTEXITCODE
27 -}
28 -exit $ret
1 -#!/bin/sh
2 -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
3 -
4 -case `uname` in
5 - *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
6 -esac
7 -
8 -if [ -x "$basedir/node" ]; then
9 - exec "$basedir/node" "$basedir/../sshpk/bin/sshpk-verify" "$@"
10 -else
11 - exec node "$basedir/../sshpk/bin/sshpk-verify" "$@"
12 -fi
1 -@ECHO off
2 -GOTO start
3 -:find_dp0
4 -SET dp0=%~dp0
5 -EXIT /b
6 -:start
7 -SETLOCAL
8 -CALL :find_dp0
9 -
10 -IF EXIST "%dp0%\node.exe" (
11 - SET "_prog=%dp0%\node.exe"
12 -) ELSE (
13 - SET "_prog=node"
14 - SET PATHEXT=%PATHEXT:;.JS;=;%
15 -)
16 -
17 -endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\sshpk\bin\sshpk-verify" %*
1 -#!/usr/bin/env pwsh
2 -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
3 -
4 -$exe=""
5 -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
6 - # Fix case when both the Windows and Linux builds of Node
7 - # are installed in the same directory
8 - $exe=".exe"
9 -}
10 -$ret=0
11 -if (Test-Path "$basedir/node$exe") {
12 - # Support pipeline input
13 - if ($MyInvocation.ExpectingInput) {
14 - $input | & "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-verify" $args
15 - } else {
16 - & "$basedir/node$exe" "$basedir/../sshpk/bin/sshpk-verify" $args
17 - }
18 - $ret=$LASTEXITCODE
19 -} else {
20 - # Support pipeline input
21 - if ($MyInvocation.ExpectingInput) {
22 - $input | & "node$exe" "$basedir/../sshpk/bin/sshpk-verify" $args
23 - } else {
24 - & "node$exe" "$basedir/../sshpk/bin/sshpk-verify" $args
25 - }
26 - $ret=$LASTEXITCODE
27 -}
28 -exit $ret
This diff could not be displayed because it is too large.
1 -@Library('jenkins-joylib@v1.0.8') _
2 -
3 -pipeline {
4 -
5 - agent none
6 -
7 - options {
8 - buildDiscarder(logRotator(numToKeepStr: '45'))
9 - timestamps()
10 - }
11 -
12 - stages {
13 - stage('top') {
14 - parallel {
15 - stage('v4-zone') {
16 - agent {
17 - label joyCommonLabels(image_ver: '15.4.1')
18 - }
19 - tools {
20 - nodejs 'sdcnode-v4-zone'
21 - }
22 - stages {
23 - stage('check') {
24 - steps{
25 - sh('make check')
26 - }
27 - }
28 - stage('test') {
29 - steps{
30 - sh('make test')
31 - }
32 - }
33 - }
34 - }
35 -
36 - stage('v6-zone64') {
37 - agent {
38 - label joyCommonLabels(image_ver: '18.4.0')
39 - }
40 - tools {
41 - nodejs 'sdcnode-v6-zone64'
42 - }
43 - stages {
44 - stage('check') {
45 - steps{
46 - sh('make check')
47 - }
48 - }
49 - stage('test') {
50 - steps{
51 - sh('make test')
52 - }
53 - }
54 - }
55 - }
56 - }
57 - }
58 - }
59 -
60 - post {
61 - always {
62 - joySlackNotifications()
63 - }
64 - }
65 -}
1 -Copyright (c) 2011 Mark Cavage, All rights reserved.
2 -
3 -Permission is hereby granted, free of charge, to any person obtaining a copy
4 -of this software and associated documentation files (the "Software"), to deal
5 -in the Software without restriction, including without limitation the rights
6 -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 -copies of the Software, and to permit persons to whom the Software is
8 -furnished to do so, subject to the following conditions:
9 -
10 -The above copyright notice and this permission notice shall be included in
11 -all copies or substantial portions of the Software.
12 -
13 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 -THE SOFTWARE
1 -node-asn1 is a library for encoding and decoding ASN.1 datatypes in pure JS.
2 -Currently BER encoding is supported; at some point I'll likely have to do DER.
3 -
4 -## Usage
5 -
6 -Mostly, if you're *actually* needing to read and write ASN.1, you probably don't
7 -need this readme to explain what and why. If you have no idea what ASN.1 is,
8 -see this: ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
9 -
10 -The source is pretty much self-explanatory, and has read/write methods for the
11 -common types out there.
12 -
13 -### Decoding
14 -
15 -The following reads an ASN.1 sequence with a boolean.
16 -
17 - var Ber = require('asn1').Ber;
18 -
19 - var reader = new Ber.Reader(Buffer.from([0x30, 0x03, 0x01, 0x01, 0xff]));
20 -
21 - reader.readSequence();
22 - console.log('Sequence len: ' + reader.length);
23 - if (reader.peek() === Ber.Boolean)
24 - console.log(reader.readBoolean());
25 -
26 -### Encoding
27 -
28 -The following generates the same payload as above.
29 -
30 - var Ber = require('asn1').Ber;
31 -
32 - var writer = new Ber.Writer();
33 -
34 - writer.startSequence();
35 - writer.writeBoolean(true);
36 - writer.endSequence();
37 -
38 - console.log(writer.buffer);
39 -
40 -## Installation
41 -
42 - npm install asn1
43 -
44 -## License
45 -
46 -MIT.
47 -
48 -## Bugs
49 -
50 -See <https://github.com/joyent/node-asn1/issues>.
1 -// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
2 -
3 -
4 -module.exports = {
5 -
6 - newInvalidAsn1Error: function (msg) {
7 - var e = new Error();
8 - e.name = 'InvalidAsn1Error';
9 - e.message = msg || '';
10 - return e;
11 - }
12 -
13 -};
1 -// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
2 -
3 -var errors = require('./errors');
4 -var types = require('./types');
5 -
6 -var Reader = require('./reader');
7 -var Writer = require('./writer');
8 -
9 -
10 -// --- Exports
11 -
12 -module.exports = {
13 -
14 - Reader: Reader,
15 -
16 - Writer: Writer
17 -
18 -};
19 -
20 -for (var t in types) {
21 - if (types.hasOwnProperty(t))
22 - module.exports[t] = types[t];
23 -}
24 -for (var e in errors) {
25 - if (errors.hasOwnProperty(e))
26 - module.exports[e] = errors[e];
27 -}
1 -// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
2 -
3 -var assert = require('assert');
4 -var Buffer = require('safer-buffer').Buffer;
5 -
6 -var ASN1 = require('./types');
7 -var errors = require('./errors');
8 -
9 -
10 -// --- Globals
11 -
12 -var newInvalidAsn1Error = errors.newInvalidAsn1Error;
13 -
14 -
15 -
16 -// --- API
17 -
18 -function Reader(data) {
19 - if (!data || !Buffer.isBuffer(data))
20 - throw new TypeError('data must be a node Buffer');
21 -
22 - this._buf = data;
23 - this._size = data.length;
24 -
25 - // These hold the "current" state
26 - this._len = 0;
27 - this._offset = 0;
28 -}
29 -
30 -Object.defineProperty(Reader.prototype, 'length', {
31 - enumerable: true,
32 - get: function () { return (this._len); }
33 -});
34 -
35 -Object.defineProperty(Reader.prototype, 'offset', {
36 - enumerable: true,
37 - get: function () { return (this._offset); }
38 -});
39 -
40 -Object.defineProperty(Reader.prototype, 'remain', {
41 - get: function () { return (this._size - this._offset); }
42 -});
43 -
44 -Object.defineProperty(Reader.prototype, 'buffer', {
45 - get: function () { return (this._buf.slice(this._offset)); }
46 -});
47 -
48 -
49 -/**
50 - * Reads a single byte and advances offset; you can pass in `true` to make this
51 - * a "peek" operation (i.e., get the byte, but don't advance the offset).
52 - *
53 - * @param {Boolean} peek true means don't move offset.
54 - * @return {Number} the next byte, null if not enough data.
55 - */
56 -Reader.prototype.readByte = function (peek) {
57 - if (this._size - this._offset < 1)
58 - return null;
59 -
60 - var b = this._buf[this._offset] & 0xff;
61 -
62 - if (!peek)
63 - this._offset += 1;
64 -
65 - return b;
66 -};
67 -
68 -
69 -Reader.prototype.peek = function () {
70 - return this.readByte(true);
71 -};
72 -
73 -
74 -/**
75 - * Reads a (potentially) variable length off the BER buffer. This call is
76 - * not really meant to be called directly, as callers have to manipulate
77 - * the internal buffer afterwards.
78 - *
79 - * As a result of this call, you can call `Reader.length`, until the
80 - * next thing called that does a readLength.
81 - *
82 - * @return {Number} the amount of offset to advance the buffer.
83 - * @throws {InvalidAsn1Error} on bad ASN.1
84 - */
85 -Reader.prototype.readLength = function (offset) {
86 - if (offset === undefined)
87 - offset = this._offset;
88 -
89 - if (offset >= this._size)
90 - return null;
91 -
92 - var lenB = this._buf[offset++] & 0xff;
93 - if (lenB === null)
94 - return null;
95 -
96 - if ((lenB & 0x80) === 0x80) {
97 - lenB &= 0x7f;
98 -
99 - if (lenB === 0)
100 - throw newInvalidAsn1Error('Indefinite length not supported');
101 -
102 - if (lenB > 4)
103 - throw newInvalidAsn1Error('encoding too long');
104 -
105 - if (this._size - offset < lenB)
106 - return null;
107 -
108 - this._len = 0;
109 - for (var i = 0; i < lenB; i++)
110 - this._len = (this._len << 8) + (this._buf[offset++] & 0xff);
111 -
112 - } else {
113 - // Wasn't a variable length
114 - this._len = lenB;
115 - }
116 -
117 - return offset;
118 -};
119 -
120 -
121 -/**
122 - * Parses the next sequence in this BER buffer.
123 - *
124 - * To get the length of the sequence, call `Reader.length`.
125 - *
126 - * @return {Number} the sequence's tag.
127 - */
128 -Reader.prototype.readSequence = function (tag) {
129 - var seq = this.peek();
130 - if (seq === null)
131 - return null;
132 - if (tag !== undefined && tag !== seq)
133 - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
134 - ': got 0x' + seq.toString(16));
135 -
136 - var o = this.readLength(this._offset + 1); // stored in `length`
137 - if (o === null)
138 - return null;
139 -
140 - this._offset = o;
141 - return seq;
142 -};
143 -
144 -
145 -Reader.prototype.readInt = function () {
146 - return this._readTag(ASN1.Integer);
147 -};
148 -
149 -
150 -Reader.prototype.readBoolean = function () {
151 - return (this._readTag(ASN1.Boolean) === 0 ? false : true);
152 -};
153 -
154 -
155 -Reader.prototype.readEnumeration = function () {
156 - return this._readTag(ASN1.Enumeration);
157 -};
158 -
159 -
160 -Reader.prototype.readString = function (tag, retbuf) {
161 - if (!tag)
162 - tag = ASN1.OctetString;
163 -
164 - var b = this.peek();
165 - if (b === null)
166 - return null;
167 -
168 - if (b !== tag)
169 - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
170 - ': got 0x' + b.toString(16));
171 -
172 - var o = this.readLength(this._offset + 1); // stored in `length`
173 -
174 - if (o === null)
175 - return null;
176 -
177 - if (this.length > this._size - o)
178 - return null;
179 -
180 - this._offset = o;
181 -
182 - if (this.length === 0)
183 - return retbuf ? Buffer.alloc(0) : '';
184 -
185 - var str = this._buf.slice(this._offset, this._offset + this.length);
186 - this._offset += this.length;
187 -
188 - return retbuf ? str : str.toString('utf8');
189 -};
190 -
191 -Reader.prototype.readOID = function (tag) {
192 - if (!tag)
193 - tag = ASN1.OID;
194 -
195 - var b = this.readString(tag, true);
196 - if (b === null)
197 - return null;
198 -
199 - var values = [];
200 - var value = 0;
201 -
202 - for (var i = 0; i < b.length; i++) {
203 - var byte = b[i] & 0xff;
204 -
205 - value <<= 7;
206 - value += byte & 0x7f;
207 - if ((byte & 0x80) === 0) {
208 - values.push(value);
209 - value = 0;
210 - }
211 - }
212 -
213 - value = values.shift();
214 - values.unshift(value % 40);
215 - values.unshift((value / 40) >> 0);
216 -
217 - return values.join('.');
218 -};
219 -
220 -
221 -Reader.prototype._readTag = function (tag) {
222 - assert.ok(tag !== undefined);
223 -
224 - var b = this.peek();
225 -
226 - if (b === null)
227 - return null;
228 -
229 - if (b !== tag)
230 - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
231 - ': got 0x' + b.toString(16));
232 -
233 - var o = this.readLength(this._offset + 1); // stored in `length`
234 - if (o === null)
235 - return null;
236 -
237 - if (this.length > 4)
238 - throw newInvalidAsn1Error('Integer too long: ' + this.length);
239 -
240 - if (this.length > this._size - o)
241 - return null;
242 - this._offset = o;
243 -
244 - var fb = this._buf[this._offset];
245 - var value = 0;
246 -
247 - for (var i = 0; i < this.length; i++) {
248 - value <<= 8;
249 - value |= (this._buf[this._offset++] & 0xff);
250 - }
251 -
252 - if ((fb & 0x80) === 0x80 && i !== 4)
253 - value -= (1 << (i * 8));
254 -
255 - return value >> 0;
256 -};
257 -
258 -
259 -
260 -// --- Exported API
261 -
262 -module.exports = Reader;
1 -// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
2 -
3 -
4 -module.exports = {
5 - EOC: 0,
6 - Boolean: 1,
7 - Integer: 2,
8 - BitString: 3,
9 - OctetString: 4,
10 - Null: 5,
11 - OID: 6,
12 - ObjectDescriptor: 7,
13 - External: 8,
14 - Real: 9, // float
15 - Enumeration: 10,
16 - PDV: 11,
17 - Utf8String: 12,
18 - RelativeOID: 13,
19 - Sequence: 16,
20 - Set: 17,
21 - NumericString: 18,
22 - PrintableString: 19,
23 - T61String: 20,
24 - VideotexString: 21,
25 - IA5String: 22,
26 - UTCTime: 23,
27 - GeneralizedTime: 24,
28 - GraphicString: 25,
29 - VisibleString: 26,
30 - GeneralString: 28,
31 - UniversalString: 29,
32 - CharacterString: 30,
33 - BMPString: 31,
34 - Constructor: 32,
35 - Context: 128
36 -};
1 -// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
2 -
3 -var assert = require('assert');
4 -var Buffer = require('safer-buffer').Buffer;
5 -var ASN1 = require('./types');
6 -var errors = require('./errors');
7 -
8 -
9 -// --- Globals
10 -
11 -var newInvalidAsn1Error = errors.newInvalidAsn1Error;
12 -
13 -var DEFAULT_OPTS = {
14 - size: 1024,
15 - growthFactor: 8
16 -};
17 -
18 -
19 -// --- Helpers
20 -
21 -function merge(from, to) {
22 - assert.ok(from);
23 - assert.equal(typeof (from), 'object');
24 - assert.ok(to);
25 - assert.equal(typeof (to), 'object');
26 -
27 - var keys = Object.getOwnPropertyNames(from);
28 - keys.forEach(function (key) {
29 - if (to[key])
30 - return;
31 -
32 - var value = Object.getOwnPropertyDescriptor(from, key);
33 - Object.defineProperty(to, key, value);
34 - });
35 -
36 - return to;
37 -}
38 -
39 -
40 -
41 -// --- API
42 -
43 -function Writer(options) {
44 - options = merge(DEFAULT_OPTS, options || {});
45 -
46 - this._buf = Buffer.alloc(options.size || 1024);
47 - this._size = this._buf.length;
48 - this._offset = 0;
49 - this._options = options;
50 -
51 - // A list of offsets in the buffer where we need to insert
52 - // sequence tag/len pairs.
53 - this._seq = [];
54 -}
55 -
56 -Object.defineProperty(Writer.prototype, 'buffer', {
57 - get: function () {
58 - if (this._seq.length)
59 - throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)');
60 -
61 - return (this._buf.slice(0, this._offset));
62 - }
63 -});
64 -
65 -Writer.prototype.writeByte = function (b) {
66 - if (typeof (b) !== 'number')
67 - throw new TypeError('argument must be a Number');
68 -
69 - this._ensure(1);
70 - this._buf[this._offset++] = b;
71 -};
72 -
73 -
74 -Writer.prototype.writeInt = function (i, tag) {
75 - if (typeof (i) !== 'number')
76 - throw new TypeError('argument must be a Number');
77 - if (typeof (tag) !== 'number')
78 - tag = ASN1.Integer;
79 -
80 - var sz = 4;
81 -
82 - while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&
83 - (sz > 1)) {
84 - sz--;
85 - i <<= 8;
86 - }
87 -
88 - if (sz > 4)
89 - throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff');
90 -
91 - this._ensure(2 + sz);
92 - this._buf[this._offset++] = tag;
93 - this._buf[this._offset++] = sz;
94 -
95 - while (sz-- > 0) {
96 - this._buf[this._offset++] = ((i & 0xff000000) >>> 24);
97 - i <<= 8;
98 - }
99 -
100 -};
101 -
102 -
103 -Writer.prototype.writeNull = function () {
104 - this.writeByte(ASN1.Null);
105 - this.writeByte(0x00);
106 -};
107 -
108 -
109 -Writer.prototype.writeEnumeration = function (i, tag) {
110 - if (typeof (i) !== 'number')
111 - throw new TypeError('argument must be a Number');
112 - if (typeof (tag) !== 'number')
113 - tag = ASN1.Enumeration;
114 -
115 - return this.writeInt(i, tag);
116 -};
117 -
118 -
119 -Writer.prototype.writeBoolean = function (b, tag) {
120 - if (typeof (b) !== 'boolean')
121 - throw new TypeError('argument must be a Boolean');
122 - if (typeof (tag) !== 'number')
123 - tag = ASN1.Boolean;
124 -
125 - this._ensure(3);
126 - this._buf[this._offset++] = tag;
127 - this._buf[this._offset++] = 0x01;
128 - this._buf[this._offset++] = b ? 0xff : 0x00;
129 -};
130 -
131 -
132 -Writer.prototype.writeString = function (s, tag) {
133 - if (typeof (s) !== 'string')
134 - throw new TypeError('argument must be a string (was: ' + typeof (s) + ')');
135 - if (typeof (tag) !== 'number')
136 - tag = ASN1.OctetString;
137 -
138 - var len = Buffer.byteLength(s);
139 - this.writeByte(tag);
140 - this.writeLength(len);
141 - if (len) {
142 - this._ensure(len);
143 - this._buf.write(s, this._offset);
144 - this._offset += len;
145 - }
146 -};
147 -
148 -
149 -Writer.prototype.writeBuffer = function (buf, tag) {
150 - if (typeof (tag) !== 'number')
151 - throw new TypeError('tag must be a number');
152 - if (!Buffer.isBuffer(buf))
153 - throw new TypeError('argument must be a buffer');
154 -
155 - this.writeByte(tag);
156 - this.writeLength(buf.length);
157 - this._ensure(buf.length);
158 - buf.copy(this._buf, this._offset, 0, buf.length);
159 - this._offset += buf.length;
160 -};
161 -
162 -
163 -Writer.prototype.writeStringArray = function (strings) {
164 - if ((!strings instanceof Array))
165 - throw new TypeError('argument must be an Array[String]');
166 -
167 - var self = this;
168 - strings.forEach(function (s) {
169 - self.writeString(s);
170 - });
171 -};
172 -
173 -// This is really to solve DER cases, but whatever for now
174 -Writer.prototype.writeOID = function (s, tag) {
175 - if (typeof (s) !== 'string')
176 - throw new TypeError('argument must be a string');
177 - if (typeof (tag) !== 'number')
178 - tag = ASN1.OID;
179 -
180 - if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
181 - throw new Error('argument is not a valid OID string');
182 -
183 - function encodeOctet(bytes, octet) {
184 - if (octet < 128) {
185 - bytes.push(octet);
186 - } else if (octet < 16384) {
187 - bytes.push((octet >>> 7) | 0x80);
188 - bytes.push(octet & 0x7F);
189 - } else if (octet < 2097152) {
190 - bytes.push((octet >>> 14) | 0x80);
191 - bytes.push(((octet >>> 7) | 0x80) & 0xFF);
192 - bytes.push(octet & 0x7F);
193 - } else if (octet < 268435456) {
194 - bytes.push((octet >>> 21) | 0x80);
195 - bytes.push(((octet >>> 14) | 0x80) & 0xFF);
196 - bytes.push(((octet >>> 7) | 0x80) & 0xFF);
197 - bytes.push(octet & 0x7F);
198 - } else {
199 - bytes.push(((octet >>> 28) | 0x80) & 0xFF);
200 - bytes.push(((octet >>> 21) | 0x80) & 0xFF);
201 - bytes.push(((octet >>> 14) | 0x80) & 0xFF);
202 - bytes.push(((octet >>> 7) | 0x80) & 0xFF);
203 - bytes.push(octet & 0x7F);
204 - }
205 - }
206 -
207 - var tmp = s.split('.');
208 - var bytes = [];
209 - bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
210 - tmp.slice(2).forEach(function (b) {
211 - encodeOctet(bytes, parseInt(b, 10));
212 - });
213 -
214 - var self = this;
215 - this._ensure(2 + bytes.length);
216 - this.writeByte(tag);
217 - this.writeLength(bytes.length);
218 - bytes.forEach(function (b) {
219 - self.writeByte(b);
220 - });
221 -};
222 -
223 -
224 -Writer.prototype.writeLength = function (len) {
225 - if (typeof (len) !== 'number')
226 - throw new TypeError('argument must be a Number');
227 -
228 - this._ensure(4);
229 -
230 - if (len <= 0x7f) {
231 - this._buf[this._offset++] = len;
232 - } else if (len <= 0xff) {
233 - this._buf[this._offset++] = 0x81;
234 - this._buf[this._offset++] = len;
235 - } else if (len <= 0xffff) {
236 - this._buf[this._offset++] = 0x82;
237 - this._buf[this._offset++] = len >> 8;
238 - this._buf[this._offset++] = len;
239 - } else if (len <= 0xffffff) {
240 - this._buf[this._offset++] = 0x83;
241 - this._buf[this._offset++] = len >> 16;
242 - this._buf[this._offset++] = len >> 8;
243 - this._buf[this._offset++] = len;
244 - } else {
245 - throw newInvalidAsn1Error('Length too long (> 4 bytes)');
246 - }
247 -};
248 -
249 -Writer.prototype.startSequence = function (tag) {
250 - if (typeof (tag) !== 'number')
251 - tag = ASN1.Sequence | ASN1.Constructor;
252 -
253 - this.writeByte(tag);
254 - this._seq.push(this._offset);
255 - this._ensure(3);
256 - this._offset += 3;
257 -};
258 -
259 -
260 -Writer.prototype.endSequence = function () {
261 - var seq = this._seq.pop();
262 - var start = seq + 3;
263 - var len = this._offset - start;
264 -
265 - if (len <= 0x7f) {
266 - this._shift(start, len, -2);
267 - this._buf[seq] = len;
268 - } else if (len <= 0xff) {
269 - this._shift(start, len, -1);
270 - this._buf[seq] = 0x81;
271 - this._buf[seq + 1] = len;
272 - } else if (len <= 0xffff) {
273 - this._buf[seq] = 0x82;
274 - this._buf[seq + 1] = len >> 8;
275 - this._buf[seq + 2] = len;
276 - } else if (len <= 0xffffff) {
277 - this._shift(start, len, 1);
278 - this._buf[seq] = 0x83;
279 - this._buf[seq + 1] = len >> 16;
280 - this._buf[seq + 2] = len >> 8;
281 - this._buf[seq + 3] = len;
282 - } else {
283 - throw newInvalidAsn1Error('Sequence too long');
284 - }
285 -};
286 -
287 -
288 -Writer.prototype._shift = function (start, len, shift) {
289 - assert.ok(start !== undefined);
290 - assert.ok(len !== undefined);
291 - assert.ok(shift);
292 -
293 - this._buf.copy(this._buf, start + shift, start, start + len);
294 - this._offset += shift;
295 -};
296 -
297 -Writer.prototype._ensure = function (len) {
298 - assert.ok(len);
299 -
300 - if (this._size - this._offset < len) {
301 - var sz = this._size * this._options.growthFactor;
302 - if (sz - this._offset < len)
303 - sz += len;
304 -
305 - var buf = Buffer.alloc(sz);
306 -
307 - this._buf.copy(buf, 0, 0, this._offset);
308 - this._buf = buf;
309 - this._size = sz;
310 - }
311 -};
312 -
313 -
314 -
315 -// --- Exported API
316 -
317 -module.exports = Writer;
1 -// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
2 -
3 -// If you have no idea what ASN.1 or BER is, see this:
4 -// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
5 -
6 -var Ber = require('./ber/index');
7 -
8 -
9 -
10 -// --- Exported API
11 -
12 -module.exports = {
13 -
14 - Ber: Ber,
15 -
16 - BerReader: Ber.Reader,
17 -
18 - BerWriter: Ber.Writer
19 -
20 -};
1 -{
2 - "author": "Joyent (joyent.com)",
3 - "contributors": [
4 - "Mark Cavage <mcavage@gmail.com>",
5 - "David Gwynne <loki@animata.net>",
6 - "Yunong Xiao <yunong@joyent.com>",
7 - "Alex Wilson <alex.wilson@joyent.com>"
8 - ],
9 - "name": "asn1",
10 - "description": "Contains parsers and serializers for ASN.1 (currently BER only)",
11 - "version": "0.2.6",
12 - "repository": {
13 - "type": "git",
14 - "url": "https://github.com/joyent/node-asn1.git"
15 - },
16 - "main": "lib/index.js",
17 - "dependencies": {
18 - "safer-buffer": "~2.1.0"
19 - },
20 - "devDependencies": {
21 - "istanbul": "^0.3.6",
22 - "faucet": "0.0.1",
23 - "tape": "^3.5.0",
24 - "eslint": "2.13.1",
25 - "eslint-plugin-joyent": "~1.3.0"
26 - },
27 - "scripts": {
28 - "test": "./node_modules/.bin/tape ./test/ber/*.test.js"
29 - },
30 - "license": "MIT"
31 -}
1 -Dave Eddy <dave@daveeddy.com>
2 -Fred Kuo <fred.kuo@joyent.com>
3 -Lars-Magnus Skog <ralphtheninja@riseup.net>
4 -Mark Cavage <mcavage@gmail.com>
5 -Patrick Mooney <pmooney@pfmooney.com>
6 -Rob Gulewich <robert.gulewich@joyent.com>
1 -# assert-plus Changelog
2 -
3 -## 1.0.0
4 -
5 -- *BREAKING* assert.number (and derivatives) now accept Infinity as valid input
6 -- Add assert.finite check. Previous assert.number callers should use this if
7 - they expect Infinity inputs to throw.
8 -
9 -## 0.2.0
10 -
11 -- Fix `assert.object(null)` so it throws
12 -- Fix optional/arrayOf exports for non-type-of asserts
13 -- Add optiona/arrayOf exports for Stream/Date/Regex/uuid
14 -- Add basic unit test coverage
1 -# assert-plus
2 -
3 -This library is a super small wrapper over node's assert module that has two
4 -things: (1) the ability to disable assertions with the environment variable
5 -NODE\_NDEBUG, and (2) some API wrappers for argument testing. Like
6 -`assert.string(myArg, 'myArg')`. As a simple example, most of my code looks
7 -like this:
8 -
9 -```javascript
10 - var assert = require('assert-plus');
11 -
12 - function fooAccount(options, callback) {
13 - assert.object(options, 'options');
14 - assert.number(options.id, 'options.id');
15 - assert.bool(options.isManager, 'options.isManager');
16 - assert.string(options.name, 'options.name');
17 - assert.arrayOfString(options.email, 'options.email');
18 - assert.func(callback, 'callback');
19 -
20 - // Do stuff
21 - callback(null, {});
22 - }
23 -```
24 -
25 -# API
26 -
27 -All methods that *aren't* part of node's core assert API are simply assumed to
28 -take an argument, and then a string 'name' that's not a message; `AssertionError`
29 -will be thrown if the assertion fails with a message like:
30 -
31 - AssertionError: foo (string) is required
32 - at test (/home/mark/work/foo/foo.js:3:9)
33 - at Object.<anonymous> (/home/mark/work/foo/foo.js:15:1)
34 - at Module._compile (module.js:446:26)
35 - at Object..js (module.js:464:10)
36 - at Module.load (module.js:353:31)
37 - at Function._load (module.js:311:12)
38 - at Array.0 (module.js:484:10)
39 - at EventEmitter._tickCallback (node.js:190:38)
40 -
41 -from:
42 -
43 -```javascript
44 - function test(foo) {
45 - assert.string(foo, 'foo');
46 - }
47 -```
48 -
49 -There you go. You can check that arrays are of a homogeneous type with `Arrayof$Type`:
50 -
51 -```javascript
52 - function test(foo) {
53 - assert.arrayOfString(foo, 'foo');
54 - }
55 -```
56 -
57 -You can assert IFF an argument is not `undefined` (i.e., an optional arg):
58 -
59 -```javascript
60 - assert.optionalString(foo, 'foo');
61 -```
62 -
63 -Lastly, you can opt-out of assertion checking altogether by setting the
64 -environment variable `NODE_NDEBUG=1`. This is pseudo-useful if you have
65 -lots of assertions, and don't want to pay `typeof ()` taxes to v8 in
66 -production. Be advised: The standard functions re-exported from `assert` are
67 -also disabled in assert-plus if NDEBUG is specified. Using them directly from
68 -the `assert` module avoids this behavior.
69 -
70 -The complete list of APIs is:
71 -
72 -* assert.array
73 -* assert.bool
74 -* assert.buffer
75 -* assert.func
76 -* assert.number
77 -* assert.finite
78 -* assert.object
79 -* assert.string
80 -* assert.stream
81 -* assert.date
82 -* assert.regexp
83 -* assert.uuid
84 -* assert.arrayOfArray
85 -* assert.arrayOfBool
86 -* assert.arrayOfBuffer
87 -* assert.arrayOfFunc
88 -* assert.arrayOfNumber
89 -* assert.arrayOfFinite
90 -* assert.arrayOfObject
91 -* assert.arrayOfString
92 -* assert.arrayOfStream
93 -* assert.arrayOfDate
94 -* assert.arrayOfRegexp
95 -* assert.arrayOfUuid
96 -* assert.optionalArray
97 -* assert.optionalBool
98 -* assert.optionalBuffer
99 -* assert.optionalFunc
100 -* assert.optionalNumber
101 -* assert.optionalFinite
102 -* assert.optionalObject
103 -* assert.optionalString
104 -* assert.optionalStream
105 -* assert.optionalDate
106 -* assert.optionalRegexp
107 -* assert.optionalUuid
108 -* assert.optionalArrayOfArray
109 -* assert.optionalArrayOfBool
110 -* assert.optionalArrayOfBuffer
111 -* assert.optionalArrayOfFunc
112 -* assert.optionalArrayOfNumber
113 -* assert.optionalArrayOfFinite
114 -* assert.optionalArrayOfObject
115 -* assert.optionalArrayOfString
116 -* assert.optionalArrayOfStream
117 -* assert.optionalArrayOfDate
118 -* assert.optionalArrayOfRegexp
119 -* assert.optionalArrayOfUuid
120 -* assert.AssertionError
121 -* assert.fail
122 -* assert.ok
123 -* assert.equal
124 -* assert.notEqual
125 -* assert.deepEqual
126 -* assert.notDeepEqual
127 -* assert.strictEqual
128 -* assert.notStrictEqual
129 -* assert.throws
130 -* assert.doesNotThrow
131 -* assert.ifError
132 -
133 -# Installation
134 -
135 - npm install assert-plus
136 -
137 -## License
138 -
139 -The MIT License (MIT)
140 -Copyright (c) 2012 Mark Cavage
141 -
142 -Permission is hereby granted, free of charge, to any person obtaining a copy of
143 -this software and associated documentation files (the "Software"), to deal in
144 -the Software without restriction, including without limitation the rights to
145 -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
146 -the Software, and to permit persons to whom the Software is furnished to do so,
147 -subject to the following conditions:
148 -
149 -The above copyright notice and this permission notice shall be included in all
150 -copies or substantial portions of the Software.
151 -
152 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
153 -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
154 -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
155 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
156 -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
157 -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
158 -SOFTWARE.
159 -
160 -## Bugs
161 -
162 -See <https://github.com/mcavage/node-assert-plus/issues>.
1 -// Copyright (c) 2012, Mark Cavage. All rights reserved.
2 -// Copyright 2015 Joyent, Inc.
3 -
4 -var assert = require('assert');
5 -var Stream = require('stream').Stream;
6 -var util = require('util');
7 -
8 -
9 -///--- Globals
10 -
11 -/* JSSTYLED */
12 -var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
13 -
14 -
15 -///--- Internal
16 -
17 -function _capitalize(str) {
18 - return (str.charAt(0).toUpperCase() + str.slice(1));
19 -}
20 -
21 -function _toss(name, expected, oper, arg, actual) {
22 - throw new assert.AssertionError({
23 - message: util.format('%s (%s) is required', name, expected),
24 - actual: (actual === undefined) ? typeof (arg) : actual(arg),
25 - expected: expected,
26 - operator: oper || '===',
27 - stackStartFunction: _toss.caller
28 - });
29 -}
30 -
31 -function _getClass(arg) {
32 - return (Object.prototype.toString.call(arg).slice(8, -1));
33 -}
34 -
35 -function noop() {
36 - // Why even bother with asserts?
37 -}
38 -
39 -
40 -///--- Exports
41 -
42 -var types = {
43 - bool: {
44 - check: function (arg) { return typeof (arg) === 'boolean'; }
45 - },
46 - func: {
47 - check: function (arg) { return typeof (arg) === 'function'; }
48 - },
49 - string: {
50 - check: function (arg) { return typeof (arg) === 'string'; }
51 - },
52 - object: {
53 - check: function (arg) {
54 - return typeof (arg) === 'object' && arg !== null;
55 - }
56 - },
57 - number: {
58 - check: function (arg) {
59 - return typeof (arg) === 'number' && !isNaN(arg);
60 - }
61 - },
62 - finite: {
63 - check: function (arg) {
64 - return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
65 - }
66 - },
67 - buffer: {
68 - check: function (arg) { return Buffer.isBuffer(arg); },
69 - operator: 'Buffer.isBuffer'
70 - },
71 - array: {
72 - check: function (arg) { return Array.isArray(arg); },
73 - operator: 'Array.isArray'
74 - },
75 - stream: {
76 - check: function (arg) { return arg instanceof Stream; },
77 - operator: 'instanceof',
78 - actual: _getClass
79 - },
80 - date: {
81 - check: function (arg) { return arg instanceof Date; },
82 - operator: 'instanceof',
83 - actual: _getClass
84 - },
85 - regexp: {
86 - check: function (arg) { return arg instanceof RegExp; },
87 - operator: 'instanceof',
88 - actual: _getClass
89 - },
90 - uuid: {
91 - check: function (arg) {
92 - return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
93 - },
94 - operator: 'isUUID'
95 - }
96 -};
97 -
98 -function _setExports(ndebug) {
99 - var keys = Object.keys(types);
100 - var out;
101 -
102 - /* re-export standard assert */
103 - if (process.env.NODE_NDEBUG) {
104 - out = noop;
105 - } else {
106 - out = function (arg, msg) {
107 - if (!arg) {
108 - _toss(msg, 'true', arg);
109 - }
110 - };
111 - }
112 -
113 - /* standard checks */
114 - keys.forEach(function (k) {
115 - if (ndebug) {
116 - out[k] = noop;
117 - return;
118 - }
119 - var type = types[k];
120 - out[k] = function (arg, msg) {
121 - if (!type.check(arg)) {
122 - _toss(msg, k, type.operator, arg, type.actual);
123 - }
124 - };
125 - });
126 -
127 - /* optional checks */
128 - keys.forEach(function (k) {
129 - var name = 'optional' + _capitalize(k);
130 - if (ndebug) {
131 - out[name] = noop;
132 - return;
133 - }
134 - var type = types[k];
135 - out[name] = function (arg, msg) {
136 - if (arg === undefined || arg === null) {
137 - return;
138 - }
139 - if (!type.check(arg)) {
140 - _toss(msg, k, type.operator, arg, type.actual);
141 - }
142 - };
143 - });
144 -
145 - /* arrayOf checks */
146 - keys.forEach(function (k) {
147 - var name = 'arrayOf' + _capitalize(k);
148 - if (ndebug) {
149 - out[name] = noop;
150 - return;
151 - }
152 - var type = types[k];
153 - var expected = '[' + k + ']';
154 - out[name] = function (arg, msg) {
155 - if (!Array.isArray(arg)) {
156 - _toss(msg, expected, type.operator, arg, type.actual);
157 - }
158 - var i;
159 - for (i = 0; i < arg.length; i++) {
160 - if (!type.check(arg[i])) {
161 - _toss(msg, expected, type.operator, arg, type.actual);
162 - }
163 - }
164 - };
165 - });
166 -
167 - /* optionalArrayOf checks */
168 - keys.forEach(function (k) {
169 - var name = 'optionalArrayOf' + _capitalize(k);
170 - if (ndebug) {
171 - out[name] = noop;
172 - return;
173 - }
174 - var type = types[k];
175 - var expected = '[' + k + ']';
176 - out[name] = function (arg, msg) {
177 - if (arg === undefined || arg === null) {
178 - return;
179 - }
180 - if (!Array.isArray(arg)) {
181 - _toss(msg, expected, type.operator, arg, type.actual);
182 - }
183 - var i;
184 - for (i = 0; i < arg.length; i++) {
185 - if (!type.check(arg[i])) {
186 - _toss(msg, expected, type.operator, arg, type.actual);
187 - }
188 - }
189 - };
190 - });
191 -
192 - /* re-export built-in assertions */
193 - Object.keys(assert).forEach(function (k) {
194 - if (k === 'AssertionError') {
195 - out[k] = assert[k];
196 - return;
197 - }
198 - if (ndebug) {
199 - out[k] = noop;
200 - return;
201 - }
202 - out[k] = assert[k];
203 - });
204 -
205 - /* export ourselves (for unit tests _only_) */
206 - out._setExports = _setExports;
207 -
208 - return out;
209 -}
210 -
211 -module.exports = _setExports(process.env.NODE_NDEBUG);
1 -{
2 - "author": "Mark Cavage <mcavage@gmail.com>",
3 - "name": "assert-plus",
4 - "description": "Extra assertions on top of node's assert module",
5 - "version": "1.0.0",
6 - "license": "MIT",
7 - "main": "./assert.js",
8 - "devDependencies": {
9 - "tape": "4.2.2",
10 - "faucet": "0.0.1"
11 - },
12 - "optionalDependencies": {},
13 - "scripts": {
14 - "test": "./node_modules/.bin/tape tests/*.js | ./node_modules/.bin/faucet"
15 - },
16 - "repository": {
17 - "type": "git",
18 - "url": "https://github.com/mcavage/node-assert-plus.git"
19 - },
20 - "engines": {
21 - "node": ">=0.8"
22 - }
23 -}
1 -Apache License
2 -
3 -Version 2.0, January 2004
4 -
5 -http://www.apache.org/licenses/
6 -
7 -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8 -
9 -1. Definitions.
10 -
11 -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12 -
13 -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14 -
15 -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16 -
17 -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18 -
19 -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20 -
21 -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22 -
23 -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24 -
25 -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26 -
27 -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28 -
29 -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30 -
31 -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32 -
33 -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34 -
35 -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36 -
37 -You must give any other recipients of the Work or Derivative Works a copy of this License; and
38 -
39 -You must cause any modified files to carry prominent notices stating that You changed the files; and
40 -
41 -You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42 -
43 -If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44 -
45 -5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46 -
47 -6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48 -
49 -7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50 -
51 -8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52 -
53 -9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54 -
55 -END OF TERMS AND CONDITIONS
...\ No newline at end of file ...\ No newline at end of file
1 -aws-sign
2 -========
3 -
4 -AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.
1 -
2 -/*!
3 - * Copyright 2010 LearnBoost <dev@learnboost.com>
4 - *
5 - * Licensed under the Apache License, Version 2.0 (the "License");
6 - * you may not use this file except in compliance with the License.
7 - * You may obtain a copy of the License at
8 - *
9 - * http://www.apache.org/licenses/LICENSE-2.0
10 - *
11 - * Unless required by applicable law or agreed to in writing, software
12 - * distributed under the License is distributed on an "AS IS" BASIS,
13 - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 - * See the License for the specific language governing permissions and
15 - * limitations under the License.
16 - */
17 -
18 -/**
19 - * Module dependencies.
20 - */
21 -
22 -var crypto = require('crypto')
23 - , parse = require('url').parse
24 - ;
25 -
26 -/**
27 - * Valid keys.
28 - */
29 -
30 -var keys =
31 - [ 'acl'
32 - , 'location'
33 - , 'logging'
34 - , 'notification'
35 - , 'partNumber'
36 - , 'policy'
37 - , 'requestPayment'
38 - , 'torrent'
39 - , 'uploadId'
40 - , 'uploads'
41 - , 'versionId'
42 - , 'versioning'
43 - , 'versions'
44 - , 'website'
45 - ]
46 -
47 -/**
48 - * Return an "Authorization" header value with the given `options`
49 - * in the form of "AWS <key>:<signature>"
50 - *
51 - * @param {Object} options
52 - * @return {String}
53 - * @api private
54 - */
55 -
56 -function authorization (options) {
57 - return 'AWS ' + options.key + ':' + sign(options)
58 -}
59 -
60 -module.exports = authorization
61 -module.exports.authorization = authorization
62 -
63 -/**
64 - * Simple HMAC-SHA1 Wrapper
65 - *
66 - * @param {Object} options
67 - * @return {String}
68 - * @api private
69 - */
70 -
71 -function hmacSha1 (options) {
72 - return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
73 -}
74 -
75 -module.exports.hmacSha1 = hmacSha1
76 -
77 -/**
78 - * Create a base64 sha1 HMAC for `options`.
79 - *
80 - * @param {Object} options
81 - * @return {String}
82 - * @api private
83 - */
84 -
85 -function sign (options) {
86 - options.message = stringToSign(options)
87 - return hmacSha1(options)
88 -}
89 -module.exports.sign = sign
90 -
91 -/**
92 - * Create a base64 sha1 HMAC for `options`.
93 - *
94 - * Specifically to be used with S3 presigned URLs
95 - *
96 - * @param {Object} options
97 - * @return {String}
98 - * @api private
99 - */
100 -
101 -function signQuery (options) {
102 - options.message = queryStringToSign(options)
103 - return hmacSha1(options)
104 -}
105 -module.exports.signQuery= signQuery
106 -
107 -/**
108 - * Return a string for sign() with the given `options`.
109 - *
110 - * Spec:
111 - *
112 - * <verb>\n
113 - * <md5>\n
114 - * <content-type>\n
115 - * <date>\n
116 - * [headers\n]
117 - * <resource>
118 - *
119 - * @param {Object} options
120 - * @return {String}
121 - * @api private
122 - */
123 -
124 -function stringToSign (options) {
125 - var headers = options.amazonHeaders || ''
126 - if (headers) headers += '\n'
127 - var r =
128 - [ options.verb
129 - , options.md5
130 - , options.contentType
131 - , options.date ? options.date.toUTCString() : ''
132 - , headers + options.resource
133 - ]
134 - return r.join('\n')
135 -}
136 -module.exports.stringToSign = stringToSign
137 -
138 -/**
139 - * Return a string for sign() with the given `options`, but is meant exclusively
140 - * for S3 presigned URLs
141 - *
142 - * Spec:
143 - *
144 - * <date>\n
145 - * <resource>
146 - *
147 - * @param {Object} options
148 - * @return {String}
149 - * @api private
150 - */
151 -
152 -function queryStringToSign (options){
153 - return 'GET\n\n\n' + options.date + '\n' + options.resource
154 -}
155 -module.exports.queryStringToSign = queryStringToSign
156 -
157 -/**
158 - * Perform the following:
159 - *
160 - * - ignore non-amazon headers
161 - * - lowercase fields
162 - * - sort lexicographically
163 - * - trim whitespace between ":"
164 - * - join with newline
165 - *
166 - * @param {Object} headers
167 - * @return {String}
168 - * @api private
169 - */
170 -
171 -function canonicalizeHeaders (headers) {
172 - var buf = []
173 - , fields = Object.keys(headers)
174 - ;
175 - for (var i = 0, len = fields.length; i < len; ++i) {
176 - var field = fields[i]
177 - , val = headers[field]
178 - , field = field.toLowerCase()
179 - ;
180 - if (0 !== field.indexOf('x-amz')) continue
181 - buf.push(field + ':' + val)
182 - }
183 - return buf.sort().join('\n')
184 -}
185 -module.exports.canonicalizeHeaders = canonicalizeHeaders
186 -
187 -/**
188 - * Perform the following:
189 - *
190 - * - ignore non sub-resources
191 - * - sort lexicographically
192 - *
193 - * @param {String} resource
194 - * @return {String}
195 - * @api private
196 - */
197 -
198 -function canonicalizeResource (resource) {
199 - var url = parse(resource, true)
200 - , path = url.pathname
201 - , buf = []
202 - ;
203 -
204 - Object.keys(url.query).forEach(function(key){
205 - if (!~keys.indexOf(key)) return
206 - var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key])
207 - buf.push(key + val)
208 - })
209 -
210 - return path + (buf.length ? '?' + buf.sort().join('&') : '')
211 -}
212 -module.exports.canonicalizeResource = canonicalizeResource
1 -{
2 - "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (http://www.futurealoof.com)",
3 - "name": "aws-sign2",
4 - "description": "AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.",
5 - "version": "0.7.0",
6 - "repository": {
7 - "url": "https://github.com/mikeal/aws-sign"
8 - },
9 - "license": "Apache-2.0",
10 - "main": "index.js",
11 - "dependencies": {},
12 - "devDependencies": {},
13 - "optionalDependencies": {},
14 - "engines": {
15 - "node": "*"
16 - }
17 -}
1 -# These are supported funding model platforms
2 -
3 -github: mhart
1 -language: node_js
2 -node_js:
3 - - "0.10"
4 - - "0.12"
5 - - "4"
6 - - "6"
7 - - "8"
8 - - "10"
9 - - "12"
1 -Copyright 2013 Michael Hart (michael.hart.au@gmail.com)
2 -
3 -Permission is hereby granted, free of charge, to any person obtaining a copy of
4 -this software and associated documentation files (the "Software"), to deal in
5 -the Software without restriction, including without limitation the rights to
6 -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 -of the Software, and to permit persons to whom the Software is furnished to do
8 -so, subject to the following conditions:
9 -
10 -The above copyright notice and this permission notice shall be included in all
11 -copies or substantial portions of the Software.
12 -
13 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 -SOFTWARE.
1 -aws4
2 -----
3 -
4 -[![Build Status](https://api.travis-ci.org/mhart/aws4.png?branch=master)](https://travis-ci.org/github/mhart/aws4)
5 -
6 -A small utility to sign vanilla Node.js http(s) request options using Amazon's
7 -[AWS Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html).
8 -
9 -If you want to sign and send AWS requests in a modern browser, or an environment like [Cloudflare Workers](https://developers.cloudflare.com/workers/), then check out [aws4fetch](https://github.com/mhart/aws4fetch) – otherwise you can also bundle this library for use [in older browsers](./browser).
10 -
11 -The only AWS service that *doesn't* support v4 as of 2020-05-22 is
12 -[SimpleDB](https://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API.html)
13 -(it only supports [AWS Signature Version 2](https://github.com/mhart/aws2)).
14 -
15 -It also provides defaults for a number of core AWS headers and
16 -request parameters, making it very easy to query AWS services, or
17 -build out a fully-featured AWS library.
18 -
19 -Example
20 --------
21 -
22 -```javascript
23 -var https = require('https')
24 -var aws4 = require('aws4')
25 -
26 -// to illustrate usage, we'll create a utility function to request and pipe to stdout
27 -function request(opts) { https.request(opts, function(res) { res.pipe(process.stdout) }).end(opts.body || '') }
28 -
29 -// aws4 will sign an options object as you'd pass to http.request, with an AWS service and region
30 -var opts = { host: 'my-bucket.s3.us-west-1.amazonaws.com', path: '/my-object', service: 's3', region: 'us-west-1' }
31 -
32 -// aws4.sign() will sign and modify these options, ready to pass to http.request
33 -aws4.sign(opts, { accessKeyId: '', secretAccessKey: '' })
34 -
35 -// or it can get credentials from process.env.AWS_ACCESS_KEY_ID, etc
36 -aws4.sign(opts)
37 -
38 -// for most AWS services, aws4 can figure out the service and region if you pass a host
39 -opts = { host: 'my-bucket.s3.us-west-1.amazonaws.com', path: '/my-object' }
40 -
41 -// usually it will add/modify request headers, but you can also sign the query:
42 -opts = { host: 'my-bucket.s3.amazonaws.com', path: '/?X-Amz-Expires=12345', signQuery: true }
43 -
44 -// and for services with simple hosts, aws4 can infer the host from service and region:
45 -opts = { service: 'sqs', region: 'us-east-1', path: '/?Action=ListQueues' }
46 -
47 -// and if you're using us-east-1, it's the default:
48 -opts = { service: 'sqs', path: '/?Action=ListQueues' }
49 -
50 -aws4.sign(opts)
51 -console.log(opts)
52 -/*
53 -{
54 - host: 'sqs.us-east-1.amazonaws.com',
55 - path: '/?Action=ListQueues',
56 - headers: {
57 - Host: 'sqs.us-east-1.amazonaws.com',
58 - 'X-Amz-Date': '20121226T061030Z',
59 - Authorization: 'AWS4-HMAC-SHA256 Credential=ABCDEF/20121226/us-east-1/sqs/aws4_request, ...'
60 - }
61 -}
62 -*/
63 -
64 -// we can now use this to query AWS
65 -request(opts)
66 -/*
67 -<?xml version="1.0"?>
68 -<ListQueuesResponse xmlns="https://queue.amazonaws.com/doc/2012-11-05/">
69 -...
70 -*/
71 -
72 -// aws4 can infer the HTTP method if a body is passed in
73 -// method will be POST and Content-Type: 'application/x-www-form-urlencoded; charset=utf-8'
74 -request(aws4.sign({ service: 'iam', body: 'Action=ListGroups&Version=2010-05-08' }))
75 -/*
76 -<ListGroupsResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/">
77 -...
78 -*/
79 -
80 -// you can specify any custom option or header as per usual
81 -request(aws4.sign({
82 - service: 'dynamodb',
83 - region: 'ap-southeast-2',
84 - method: 'POST',
85 - path: '/',
86 - headers: {
87 - 'Content-Type': 'application/x-amz-json-1.0',
88 - 'X-Amz-Target': 'DynamoDB_20120810.ListTables'
89 - },
90 - body: '{}'
91 -}))
92 -/*
93 -{"TableNames":[]}
94 -...
95 -*/
96 -
97 -// The raw RequestSigner can be used to generate CodeCommit Git passwords
98 -var signer = new aws4.RequestSigner({
99 - service: 'codecommit',
100 - host: 'git-codecommit.us-east-1.amazonaws.com',
101 - method: 'GIT',
102 - path: '/v1/repos/MyAwesomeRepo',
103 -})
104 -var password = signer.getDateTime() + 'Z' + signer.signature()
105 -
106 -// see example.js for examples with other services
107 -```
108 -
109 -API
110 ----
111 -
112 -### aws4.sign(requestOptions, [credentials])
113 -
114 -Calculates and populates any necessary AWS headers and/or request
115 -options on `requestOptions`. Returns `requestOptions` as a convenience for chaining.
116 -
117 -`requestOptions` is an object holding the same options that the Node.js
118 -[http.request](https://nodejs.org/docs/latest/api/http.html#http_http_request_options_callback)
119 -function takes.
120 -
121 -The following properties of `requestOptions` are used in the signing or
122 -populated if they don't already exist:
123 -
124 -- `hostname` or `host` (will try to be determined from `service` and `region` if not given)
125 -- `method` (will use `'GET'` if not given or `'POST'` if there is a `body`)
126 -- `path` (will use `'/'` if not given)
127 -- `body` (will use `''` if not given)
128 -- `service` (will try to be calculated from `hostname` or `host` if not given)
129 -- `region` (will try to be calculated from `hostname` or `host` or use `'us-east-1'` if not given)
130 -- `signQuery` (to sign the query instead of adding an `Authorization` header, defaults to false)
131 -- `headers['Host']` (will use `hostname` or `host` or be calculated if not given)
132 -- `headers['Content-Type']` (will use `'application/x-www-form-urlencoded; charset=utf-8'`
133 - if not given and there is a `body`)
134 -- `headers['Date']` (used to calculate the signature date if given, otherwise `new Date` is used)
135 -
136 -Your AWS credentials (which can be found in your
137 -[AWS console](https://portal.aws.amazon.com/gp/aws/securityCredentials))
138 -can be specified in one of two ways:
139 -
140 -- As the second argument, like this:
141 -
142 -```javascript
143 -aws4.sign(requestOptions, {
144 - secretAccessKey: "<your-secret-access-key>",
145 - accessKeyId: "<your-access-key-id>",
146 - sessionToken: "<your-session-token>"
147 -})
148 -```
149 -
150 -- From `process.env`, such as this:
151 -
152 -```
153 -export AWS_ACCESS_KEY_ID="<your-access-key-id>"
154 -export AWS_SECRET_ACCESS_KEY="<your-secret-access-key>"
155 -export AWS_SESSION_TOKEN="<your-session-token>"
156 -```
157 -
158 -(will also use `AWS_ACCESS_KEY` and `AWS_SECRET_KEY` if available)
159 -
160 -The `sessionToken` property and `AWS_SESSION_TOKEN` environment variable are optional for signing
161 -with [IAM STS temporary credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html).
162 -
163 -Installation
164 -------------
165 -
166 -With [npm](https://www.npmjs.com/) do:
167 -
168 -```
169 -npm install aws4
170 -```
171 -
172 -Can also be used [in the browser](./browser).
173 -
174 -Thanks
175 -------
176 -
177 -Thanks to [@jed](https://github.com/jed) for his
178 -[dynamo-client](https://github.com/jed/dynamo-client) lib where I first
179 -committed and subsequently extracted this code.
180 -
181 -Also thanks to the
182 -[official Node.js AWS SDK](https://github.com/aws/aws-sdk-js) for giving
183 -me a start on implementing the v4 signature.
This diff is collapsed. Click to expand it.
1 -module.exports = function(size) {
2 - return new LruCache(size)
3 -}
4 -
5 -function LruCache(size) {
6 - this.capacity = size | 0
7 - this.map = Object.create(null)
8 - this.list = new DoublyLinkedList()
9 -}
10 -
11 -LruCache.prototype.get = function(key) {
12 - var node = this.map[key]
13 - if (node == null) return undefined
14 - this.used(node)
15 - return node.val
16 -}
17 -
18 -LruCache.prototype.set = function(key, val) {
19 - var node = this.map[key]
20 - if (node != null) {
21 - node.val = val
22 - } else {
23 - if (!this.capacity) this.prune()
24 - if (!this.capacity) return false
25 - node = new DoublyLinkedNode(key, val)
26 - this.map[key] = node
27 - this.capacity--
28 - }
29 - this.used(node)
30 - return true
31 -}
32 -
33 -LruCache.prototype.used = function(node) {
34 - this.list.moveToFront(node)
35 -}
36 -
37 -LruCache.prototype.prune = function() {
38 - var node = this.list.pop()
39 - if (node != null) {
40 - delete this.map[node.key]
41 - this.capacity++
42 - }
43 -}
44 -
45 -
46 -function DoublyLinkedList() {
47 - this.firstNode = null
48 - this.lastNode = null
49 -}
50 -
51 -DoublyLinkedList.prototype.moveToFront = function(node) {
52 - if (this.firstNode == node) return
53 -
54 - this.remove(node)
55 -
56 - if (this.firstNode == null) {
57 - this.firstNode = node
58 - this.lastNode = node
59 - node.prev = null
60 - node.next = null
61 - } else {
62 - node.prev = null
63 - node.next = this.firstNode
64 - node.next.prev = node
65 - this.firstNode = node
66 - }
67 -}
68 -
69 -DoublyLinkedList.prototype.pop = function() {
70 - var lastNode = this.lastNode
71 - if (lastNode != null) {
72 - this.remove(lastNode)
73 - }
74 - return lastNode
75 -}
76 -
77 -DoublyLinkedList.prototype.remove = function(node) {
78 - if (this.firstNode == node) {
79 - this.firstNode = node.next
80 - } else if (node.prev != null) {
81 - node.prev.next = node.next
82 - }
83 - if (this.lastNode == node) {
84 - this.lastNode = node.prev
85 - } else if (node.next != null) {
86 - node.next.prev = node.prev
87 - }
88 -}
89 -
90 -
91 -function DoublyLinkedNode(key, val) {
92 - this.key = key
93 - this.val = val
94 - this.prev = null
95 - this.next = null
96 -}
1 -{
2 - "name": "aws4",
3 - "version": "1.11.0",
4 - "description": "Signs and prepares requests using AWS Signature Version 4",
5 - "author": "Michael Hart <michael.hart.au@gmail.com> (https://github.com/mhart)",
6 - "license": "MIT",
7 - "repository": "github:mhart/aws4",
8 - "main": "aws4.js",
9 - "scripts": {
10 - "test": "mocha ./test/fast.js -R list",
11 - "integration": "node ./test/slow.js"
12 - },
13 - "devDependencies": {
14 - "mocha": "^2.5.3",
15 - "should": "^8.4.0"
16 - }
17 -}
1 -# Contributing
2 -
3 -This repository uses [cr.joyent.us](https://cr.joyent.us) (Gerrit) for new
4 -changes. Anyone can submit changes. To get started, see the [cr.joyent.us user
5 -guide](https://github.com/joyent/joyent-gerrit/blob/master/docs/user/README.md).
6 -This repo does not use GitHub pull requests.
7 -
8 -See the [Joyent Engineering
9 -Guidelines](https://github.com/joyent/eng/blob/master/docs/index.md) for general
10 -best practices expected in this repository.
11 -
12 -If you're changing something non-trivial or user-facing, you may want to submit
13 -an issue first.
1 -The Blowfish portions are under the following license:
2 -
3 -Blowfish block cipher for OpenBSD
4 -Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
5 -All rights reserved.
6 -
7 -Implementation advice by David Mazieres <dm@lcs.mit.edu>.
8 -
9 -Redistribution and use in source and binary forms, with or without
10 -modification, are permitted provided that the following conditions
11 -are met:
12 -1. Redistributions of source code must retain the above copyright
13 - notice, this list of conditions and the following disclaimer.
14 -2. Redistributions in binary form must reproduce the above copyright
15 - notice, this list of conditions and the following disclaimer in the
16 - documentation and/or other materials provided with the distribution.
17 -3. The name of the author may not be used to endorse or promote products
18 - derived from this software without specific prior written permission.
19 -
20 -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21 -IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 -IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24 -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 -NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 -
31 -
32 -
33 -The bcrypt_pbkdf portions are under the following license:
34 -
35 -Copyright (c) 2013 Ted Unangst <tedu@openbsd.org>
36 -
37 -Permission to use, copy, modify, and distribute this software for any
38 -purpose with or without fee is hereby granted, provided that the above
39 -copyright notice and this permission notice appear in all copies.
40 -
41 -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
42 -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
43 -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
44 -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
45 -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
46 -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
47 -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
48 -
49 -
50 -
51 -Performance improvements (Javascript-specific):
52 -
53 -Copyright 2016, Joyent Inc
54 -Author: Alex Wilson <alex.wilson@joyent.com>
55 -
56 -Permission to use, copy, modify, and distribute this software for any
57 -purpose with or without fee is hereby granted, provided that the above
58 -copyright notice and this permission notice appear in all copies.
59 -
60 -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
61 -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
62 -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
63 -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
64 -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
65 -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
66 -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1 -Port of the OpenBSD `bcrypt_pbkdf` function to pure Javascript. `npm`-ified
2 -version of [Devi Mandiri's port](https://github.com/devi/tmp/blob/master/js/bcrypt_pbkdf.js),
3 -with some minor performance improvements. The code is copied verbatim (and
4 -un-styled) from Devi's work.
5 -
6 -This product includes software developed by Niels Provos.
7 -
8 -## API
9 -
10 -### `bcrypt_pbkdf.pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds)`
11 -
12 -Derive a cryptographic key of arbitrary length from a given password and salt,
13 -using the OpenBSD `bcrypt_pbkdf` function. This is a combination of Blowfish and
14 -SHA-512.
15 -
16 -See [this article](http://www.tedunangst.com/flak/post/bcrypt-pbkdf) for
17 -further information.
18 -
19 -Parameters:
20 -
21 - * `pass`, a Uint8Array of length `passlen`
22 - * `passlen`, an integer Number
23 - * `salt`, a Uint8Array of length `saltlen`
24 - * `saltlen`, an integer Number
25 - * `key`, a Uint8Array of length `keylen`, will be filled with output
26 - * `keylen`, an integer Number
27 - * `rounds`, an integer Number, number of rounds of the PBKDF to run
28 -
29 -### `bcrypt_pbkdf.hash(sha2pass, sha2salt, out)`
30 -
31 -Calculate a Blowfish hash, given SHA2-512 output of a password and salt. Used as
32 -part of the inner round function in the PBKDF.
33 -
34 -Parameters:
35 -
36 - * `sha2pass`, a Uint8Array of length 64
37 - * `sha2salt`, a Uint8Array of length 64
38 - * `out`, a Uint8Array of length 32, will be filled with output
39 -
40 -## License
41 -
42 -This source form is a 1:1 port from the OpenBSD `blowfish.c` and `bcrypt_pbkdf.c`.
43 -As a result, it retains the original copyright and license. The two files are
44 -under slightly different (but compatible) licenses, and are here combined in
45 -one file. For each of the full license texts see `LICENSE`.
This diff is collapsed. Click to expand it.
1 -{
2 - "name": "bcrypt-pbkdf",
3 - "version": "1.0.2",
4 - "description": "Port of the OpenBSD bcrypt_pbkdf function to pure JS",
5 - "repository": {
6 - "type": "git",
7 - "url": "git://github.com/joyent/node-bcrypt-pbkdf.git"
8 - },
9 - "main": "index.js",
10 - "dependencies": {
11 - "tweetnacl": "^0.14.3"
12 - },
13 - "devDependencies": {},
14 - "license": "BSD-3-Clause"
15 -}
1 -Apache License
2 -Version 2.0, January 2004
3 -http://www.apache.org/licenses/
4 -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
5 -1. Definitions.
6 -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
7 -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
8 -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
9 -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
10 -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
11 -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
12 -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
13 -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
14 -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
15 -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
16 -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
17 -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
18 -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
19 -You must give any other recipients of the Work or Derivative Works a copy of this License; and
20 -You must cause any modified files to carry prominent notices stating that You changed the files; and
21 -You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
22 -If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
23 -5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
24 -6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
25 -7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
26 -8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
27 -9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
28 -END OF TERMS AND CONDITIONS
...\ No newline at end of file ...\ No newline at end of file
1 -## Caseless -- wrap an object to set and get property with caseless semantics but also preserve caseing.
2 -
3 -This library is incredibly useful when working with HTTP headers. It allows you to get/set/check for headers in a caseless manner while also preserving the caseing of headers the first time they are set.
4 -
5 -## Usage
6 -
7 -```javascript
8 -var headers = {}
9 - , c = caseless(headers)
10 - ;
11 -c.set('a-Header', 'asdf')
12 -c.get('a-header') === 'asdf'
13 -```
14 -
15 -## has(key)
16 -
17 -Has takes a name and if it finds a matching header will return that header name with the preserved caseing it was set with.
18 -
19 -```javascript
20 -c.has('a-header') === 'a-Header'
21 -```
22 -
23 -## set(key, value[, clobber=true])
24 -
25 -Set is fairly straight forward except that if the header exists and clobber is disabled it will add `','+value` to the existing header.
26 -
27 -```javascript
28 -c.set('a-Header', 'fdas')
29 -c.set('a-HEADER', 'more', false)
30 -c.get('a-header') === 'fdsa,more'
31 -```
32 -
33 -## swap(key)
34 -
35 -Swaps the casing of a header with the new one that is passed in.
36 -
37 -```javascript
38 -var headers = {}
39 - , c = caseless(headers)
40 - ;
41 -c.set('a-Header', 'fdas')
42 -c.swap('a-HEADER')
43 -c.has('a-header') === 'a-HEADER'
44 -headers === {'a-HEADER': 'fdas'}
45 -```
1 -function Caseless (dict) {
2 - this.dict = dict || {}
3 -}
4 -Caseless.prototype.set = function (name, value, clobber) {
5 - if (typeof name === 'object') {
6 - for (var i in name) {
7 - this.set(i, name[i], value)
8 - }
9 - } else {
10 - if (typeof clobber === 'undefined') clobber = true
11 - var has = this.has(name)
12 -
13 - if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value
14 - else this.dict[has || name] = value
15 - return has
16 - }
17 -}
18 -Caseless.prototype.has = function (name) {
19 - var keys = Object.keys(this.dict)
20 - , name = name.toLowerCase()
21 - ;
22 - for (var i=0;i<keys.length;i++) {
23 - if (keys[i].toLowerCase() === name) return keys[i]
24 - }
25 - return false
26 -}
27 -Caseless.prototype.get = function (name) {
28 - name = name.toLowerCase()
29 - var result, _key
30 - var headers = this.dict
31 - Object.keys(headers).forEach(function (key) {
32 - _key = key.toLowerCase()
33 - if (name === _key) result = headers[key]
34 - })
35 - return result
36 -}
37 -Caseless.prototype.swap = function (name) {
38 - var has = this.has(name)
39 - if (has === name) return
40 - if (!has) throw new Error('There is no header than matches "'+name+'"')
41 - this.dict[name] = this.dict[has]
42 - delete this.dict[has]
43 -}
44 -Caseless.prototype.del = function (name) {
45 - var has = this.has(name)
46 - return delete this.dict[has || name]
47 -}
48 -
49 -module.exports = function (dict) {return new Caseless(dict)}
50 -module.exports.httpify = function (resp, headers) {
51 - var c = new Caseless(headers)
52 - resp.setHeader = function (key, value, clobber) {
53 - if (typeof value === 'undefined') return
54 - return c.set(key, value, clobber)
55 - }
56 - resp.hasHeader = function (key) {
57 - return c.has(key)
58 - }
59 - resp.getHeader = function (key) {
60 - return c.get(key)
61 - }
62 - resp.removeHeader = function (key) {
63 - return c.del(key)
64 - }
65 - resp.headers = c.dict
66 - return c
67 -}
1 -{
2 - "name": "caseless",
3 - "version": "0.12.0",
4 - "description": "Caseless object set/get/has, very useful when working with HTTP headers.",
5 - "main": "index.js",
6 - "scripts": {
7 - "test": "node test.js"
8 - },
9 - "repository": {
10 - "type": "git",
11 - "url": "https://github.com/mikeal/caseless"
12 - },
13 - "keywords": [
14 - "headers",
15 - "http",
16 - "caseless"
17 - ],
18 - "test": "node test.js",
19 - "author": "Mikeal Rogers <mikeal.rogers@gmail.com>",
20 - "license": "Apache-2.0",
21 - "bugs": {
22 - "url": "https://github.com/mikeal/caseless/issues"
23 - },
24 - "devDependencies": {
25 - "tape": "^2.10.2"
26 - }
27 -}
1 -var tape = require('tape')
2 - , caseless = require('./')
3 - ;
4 -
5 -tape('set get has', function (t) {
6 - var headers = {}
7 - , c = caseless(headers)
8 - ;
9 - t.plan(17)
10 - c.set('a-Header', 'asdf')
11 - t.equal(c.get('a-header'), 'asdf')
12 - t.equal(c.has('a-header'), 'a-Header')
13 - t.ok(!c.has('nothing'))
14 - // old bug where we used the wrong regex
15 - t.ok(!c.has('a-hea'))
16 - c.set('a-header', 'fdsa')
17 - t.equal(c.get('a-header'), 'fdsa')
18 - t.equal(c.get('a-Header'), 'fdsa')
19 - c.set('a-HEADER', 'more', false)
20 - t.equal(c.get('a-header'), 'fdsa,more')
21 -
22 - t.deepEqual(headers, {'a-Header': 'fdsa,more'})
23 - c.swap('a-HEADER')
24 - t.deepEqual(headers, {'a-HEADER': 'fdsa,more'})
25 -
26 - c.set('deleteme', 'foobar')
27 - t.ok(c.has('deleteme'))
28 - t.ok(c.del('deleteme'))
29 - t.notOk(c.has('deleteme'))
30 - t.notOk(c.has('idonotexist'))
31 - t.ok(c.del('idonotexist'))
32 -
33 - c.set('tva', 'test1')
34 - c.set('tva-header', 'test2')
35 - t.equal(c.has('tva'), 'tva')
36 - t.notOk(c.has('header'))
37 -
38 - t.equal(c.get('tva'), 'test1')
39 -
40 -})
41 -
42 -tape('swap', function (t) {
43 - var headers = {}
44 - , c = caseless(headers)
45 - ;
46 - t.plan(4)
47 - // No Header to Swap.
48 - t.throws(function () {
49 - c.swap('content-type')
50 - })
51 - // Set Header.
52 - c.set('content-type', 'application/json')
53 - // Swap Header With Itself.
54 - c.swap('content-type')
55 - // Does Not Delete Itself.
56 - t.ok(c.has('content-type'))
57 - // Swap Header With a Different Header.
58 - c.swap('Content-Type')
59 - // Still Has Header.
60 - t.ok(c.has('Content-Type'))
61 - // Delete Header.
62 - c.del('Content-Type')
63 - // No Header to Swap.
64 - t.throws(function () {
65 - c.swap('content-type')
66 - })
67 -})
This diff is collapsed. Click to expand it.
1 -# This is the MIT license
2 -
3 -Copyright (c) 2013 Trent Mick. All rights reserved.
4 -Copyright (c) 2013 Joyent Inc. All rights reserved.
5 -
6 -Permission is hereby granted, free of charge, to any person obtaining a
7 -copy of this software and associated documentation files (the
8 -"Software"), to deal in the Software without restriction, including
9 -without limitation the rights to use, copy, modify, merge, publish,
10 -distribute, sublicense, and/or sell copies of the Software, and to
11 -permit persons to whom the Software is furnished to do so, subject to
12 -the following conditions:
13 -
14 -The above copyright notice and this permission notice shall be included
15 -in all copies or substantial portions of the Software.
16 -
17 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20 -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21 -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22 -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23 -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 -
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
1 -{
2 - "name": "dashdash",
3 - "description": "A light, featureful and explicit option parsing library.",
4 - "version": "1.14.1",
5 - "author": "Trent Mick <trentm@gmail.com> (http://trentm.com)",
6 - "keywords": ["option", "parser", "parsing", "cli", "command", "args",
7 - "bash", "completion"],
8 - "repository": {
9 - "type": "git",
10 - "url": "git://github.com/trentm/node-dashdash.git"
11 - },
12 - "main": "./lib/dashdash.js",
13 - "dependencies": {
14 - "assert-plus": "^1.0.0"
15 - },
16 - "devDependencies": {
17 - "nodeunit": "0.9.x"
18 - },
19 - "engines": {
20 - "node": ">=0.10"
21 - },
22 - "scripts": {
23 - "test": "nodeunit test/*.test.js"
24 - },
25 - "license": "MIT"
26 -}
1 -The MIT License (MIT)
2 -
3 -Copyright (c) 2014 Jeremie Miller
4 -
5 -Permission is hereby granted, free of charge, to any person obtaining a copy
6 -of this software and associated documentation files (the "Software"), to deal
7 -in the Software without restriction, including without limitation the rights
8 -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 -copies of the Software, and to permit persons to whom the Software is
10 -furnished to do so, subject to the following conditions:
11 -
12 -The above copyright notice and this permission notice shall be included in all
13 -copies or substantial portions of the Software.
14 -
15 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 -SOFTWARE.
...\ No newline at end of file ...\ No newline at end of file
1 -ecc-jsbn
2 -========
3 -
4 -ECC package based on [jsbn](https://github.com/andyperlitch/jsbn) from [Tom Wu](http://www-cs-students.stanford.edu/~tjw/).
5 -
6 -This is a subset of the same interface as the [node compiled module](https://github.com/quartzjer/ecc), but works in the browser too.
7 -
8 -Also uses point compression now from [https://github.com/kaielvin](https://github.com/kaielvin/jsbn-ec-point-compression).
1 -var crypto = require("crypto");
2 -var BigInteger = require("jsbn").BigInteger;
3 -var ECPointFp = require("./lib/ec.js").ECPointFp;
4 -var Buffer = require("safer-buffer").Buffer;
5 -exports.ECCurves = require("./lib/sec.js");
6 -
7 -// zero prepad
8 -function unstupid(hex,len)
9 -{
10 - return (hex.length >= len) ? hex : unstupid("0"+hex,len);
11 -}
12 -
13 -exports.ECKey = function(curve, key, isPublic)
14 -{
15 - var priv;
16 - var c = curve();
17 - var n = c.getN();
18 - var bytes = Math.floor(n.bitLength()/8);
19 -
20 - if(key)
21 - {
22 - if(isPublic)
23 - {
24 - var curve = c.getCurve();
25 -// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format
26 -// var y = key.slice(bytes+1);
27 -// this.P = new ECPointFp(curve,
28 -// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)),
29 -// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16)));
30 - this.P = curve.decodePointHex(key.toString("hex"));
31 - }else{
32 - if(key.length != bytes) return false;
33 - priv = new BigInteger(key.toString("hex"), 16);
34 - }
35 - }else{
36 - var n1 = n.subtract(BigInteger.ONE);
37 - var r = new BigInteger(crypto.randomBytes(n.bitLength()));
38 - priv = r.mod(n1).add(BigInteger.ONE);
39 - this.P = c.getG().multiply(priv);
40 - }
41 - if(this.P)
42 - {
43 -// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2);
44 -// this.PublicKey = Buffer.from("04"+pubhex,"hex");
45 - this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex");
46 - }
47 - if(priv)
48 - {
49 - this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex");
50 - this.deriveSharedSecret = function(key)
51 - {
52 - if(!key || !key.P) return false;
53 - var S = key.P.multiply(priv);
54 - return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex");
55 - }
56 - }
57 -}
58 -
1 -Licensing
2 ----------
3 -
4 -This software is covered under the following copyright:
5 -
6 -/*
7 - * Copyright (c) 2003-2005 Tom Wu
8 - * All Rights Reserved.
9 - *
10 - * Permission is hereby granted, free of charge, to any person obtaining
11 - * a copy of this software and associated documentation files (the
12 - * "Software"), to deal in the Software without restriction, including
13 - * without limitation the rights to use, copy, modify, merge, publish,
14 - * distribute, sublicense, and/or sell copies of the Software, and to
15 - * permit persons to whom the Software is furnished to do so, subject to
16 - * the following conditions:
17 - *
18 - * The above copyright notice and this permission notice shall be
19 - * included in all copies or substantial portions of the Software.
20 - *
21 - * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
22 - * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
23 - * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
24 - *
25 - * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
26 - * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
27 - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
28 - * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
29 - * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
30 - *
31 - * In addition, the following condition applies:
32 - *
33 - * All redistributions must retain an intact copy of this copyright notice
34 - * and disclaimer.
35 - */
36 -
37 -Address all questions regarding this license to:
38 -
39 - Tom Wu
40 - tjw@cs.Stanford.EDU
This diff is collapsed. Click to expand it.
1 -// Named EC curves
2 -
3 -// Requires ec.js, jsbn.js, and jsbn2.js
4 -var BigInteger = require('jsbn').BigInteger
5 -var ECCurveFp = require('./ec.js').ECCurveFp
6 -
7 -
8 -// ----------------
9 -// X9ECParameters
10 -
11 -// constructor
12 -function X9ECParameters(curve,g,n,h) {
13 - this.curve = curve;
14 - this.g = g;
15 - this.n = n;
16 - this.h = h;
17 -}
18 -
19 -function x9getCurve() {
20 - return this.curve;
21 -}
22 -
23 -function x9getG() {
24 - return this.g;
25 -}
26 -
27 -function x9getN() {
28 - return this.n;
29 -}
30 -
31 -function x9getH() {
32 - return this.h;
33 -}
34 -
35 -X9ECParameters.prototype.getCurve = x9getCurve;
36 -X9ECParameters.prototype.getG = x9getG;
37 -X9ECParameters.prototype.getN = x9getN;
38 -X9ECParameters.prototype.getH = x9getH;
39 -
40 -// ----------------
41 -// SECNamedCurves
42 -
43 -function fromHex(s) { return new BigInteger(s, 16); }
44 -
45 -function secp128r1() {
46 - // p = 2^128 - 2^97 - 1
47 - var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
48 - var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");
49 - var b = fromHex("E87579C11079F43DD824993C2CEE5ED3");
50 - //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679");
51 - var n = fromHex("FFFFFFFE0000000075A30D1B9038A115");
52 - var h = BigInteger.ONE;
53 - var curve = new ECCurveFp(p, a, b);
54 - var G = curve.decodePointHex("04"
55 - + "161FF7528B899B2D0C28607CA52C5B86"
56 - + "CF5AC8395BAFEB13C02DA292DDED7A83");
57 - return new X9ECParameters(curve, G, n, h);
58 -}
59 -
60 -function secp160k1() {
61 - // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
62 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
63 - var a = BigInteger.ZERO;
64 - var b = fromHex("7");
65 - //byte[] S = null;
66 - var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
67 - var h = BigInteger.ONE;
68 - var curve = new ECCurveFp(p, a, b);
69 - var G = curve.decodePointHex("04"
70 - + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"
71 - + "938CF935318FDCED6BC28286531733C3F03C4FEE");
72 - return new X9ECParameters(curve, G, n, h);
73 -}
74 -
75 -function secp160r1() {
76 - // p = 2^160 - 2^31 - 1
77 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");
78 - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");
79 - var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");
80 - //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345");
81 - var n = fromHex("0100000000000000000001F4C8F927AED3CA752257");
82 - var h = BigInteger.ONE;
83 - var curve = new ECCurveFp(p, a, b);
84 - var G = curve.decodePointHex("04"
85 - + "4A96B5688EF573284664698968C38BB913CBFC82"
86 - + "23A628553168947D59DCC912042351377AC5FB32");
87 - return new X9ECParameters(curve, G, n, h);
88 -}
89 -
90 -function secp192k1() {
91 - // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1
92 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");
93 - var a = BigInteger.ZERO;
94 - var b = fromHex("3");
95 - //byte[] S = null;
96 - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");
97 - var h = BigInteger.ONE;
98 - var curve = new ECCurveFp(p, a, b);
99 - var G = curve.decodePointHex("04"
100 - + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"
101 - + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D");
102 - return new X9ECParameters(curve, G, n, h);
103 -}
104 -
105 -function secp192r1() {
106 - // p = 2^192 - 2^64 - 1
107 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");
108 - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");
109 - var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");
110 - //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5");
111 - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");
112 - var h = BigInteger.ONE;
113 - var curve = new ECCurveFp(p, a, b);
114 - var G = curve.decodePointHex("04"
115 - + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"
116 - + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
117 - return new X9ECParameters(curve, G, n, h);
118 -}
119 -
120 -function secp224r1() {
121 - // p = 2^224 - 2^96 + 1
122 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");
123 - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");
124 - var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");
125 - //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
126 - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");
127 - var h = BigInteger.ONE;
128 - var curve = new ECCurveFp(p, a, b);
129 - var G = curve.decodePointHex("04"
130 - + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"
131 - + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34");
132 - return new X9ECParameters(curve, G, n, h);
133 -}
134 -
135 -function secp256r1() {
136 - // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1
137 - var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
138 - var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
139 - var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
140 - //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90");
141 - var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
142 - var h = BigInteger.ONE;
143 - var curve = new ECCurveFp(p, a, b);
144 - var G = curve.decodePointHex("04"
145 - + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"
146 - + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");
147 - return new X9ECParameters(curve, G, n, h);
148 -}
149 -
150 -// TODO: make this into a proper hashtable
151 -function getSECCurveByName(name) {
152 - if(name == "secp128r1") return secp128r1();
153 - if(name == "secp160k1") return secp160k1();
154 - if(name == "secp160r1") return secp160r1();
155 - if(name == "secp192k1") return secp192k1();
156 - if(name == "secp192r1") return secp192r1();
157 - if(name == "secp224r1") return secp224r1();
158 - if(name == "secp256r1") return secp256r1();
159 - return null;
160 -}
161 -
162 -module.exports = {
163 - "secp128r1":secp128r1,
164 - "secp160k1":secp160k1,
165 - "secp160r1":secp160r1,
166 - "secp192k1":secp192k1,
167 - "secp192r1":secp192r1,
168 - "secp224r1":secp224r1,
169 - "secp256r1":secp256r1
170 -}
1 -{
2 - "name": "ecc-jsbn",
3 - "version": "0.1.2",
4 - "description": "ECC JS code based on JSBN",
5 - "main": "index.js",
6 - "repository": {
7 - "type": "git",
8 - "url": "https://github.com/quartzjer/ecc-jsbn.git"
9 - },
10 - "keywords": [
11 - "jsbn",
12 - "ecc",
13 - "browserify"
14 - ],
15 - "author": {
16 - "name": "Jeremie Miller",
17 - "email": "jeremie@jabber.org",
18 - "url": "http://jeremie.com/"
19 - },
20 - "maintainers": [
21 - {
22 - "name": "Jeremie Miller",
23 - "email": "jeremie@jabber.org",
24 - "url": "http://jeremie.com/"
25 - },
26 - {
27 - "name": "Ryan Bennett",
28 - "url": "https://github.com/rynomad"
29 - }
30 - ],
31 - "dependencies": {
32 - "jsbn": "~0.1.0",
33 - "safer-buffer": "^2.1.0"
34 - },
35 - "license": "MIT",
36 - "bugs": {
37 - "url": "https://github.com/quartzjer/ecc-jsbn/issues"
38 - },
39 - "homepage": "https://github.com/quartzjer/ecc-jsbn"
40 -}
1 -var ecc = require("./index.js");
2 -var key1 = new ecc.ECKey(ecc.ECCurves.secp160r1);
3 -var key2 = new ecc.ECKey(ecc.ECCurves.secp160r1);
4 -console.log(key1.deriveSharedSecret(key2));
5 -var key3 = new ecc.ECKey(ecc.ECCurves.secp160r1,key1.PrivateKey);
6 -var key4 = new ecc.ECKey(ecc.ECCurves.secp160r1,key2.PublicKey,true);
7 -console.log(key3.deriveSharedSecret(key4));
8 -
9 -var key1 = new ecc.ECKey(ecc.ECCurves.secp256r1);
10 -var key2 = new ecc.ECKey(ecc.ECCurves.secp256r1);
11 -console.log(key1.deriveSharedSecret(key2));
12 -var key3 = new ecc.ECKey(ecc.ECCurves.secp256r1,key1.PrivateKey);
13 -var key4 = new ecc.ECKey(ecc.ECCurves.secp256r1,key2.PublicKey,true);
14 -console.log(key3.deriveSharedSecret(key4));
1 -root = true
2 -
3 -[*]
4 -indent_style = tab
5 -indent_size = 4
6 -end_of_line = lf
7 -charset = utf-8
8 -trim_trailing_whitespace = true
9 -insert_final_newline = true
10 -max_line_length = 150
11 -
12 -[CHANGELOG.md]
13 -indent_style = space
14 -indent_size = 2
15 -
16 -[*.json]
17 -max_line_length = off
18 -
19 -[Makefile]
20 -max_line_length = off
1 -{
2 - "root": true,
3 -
4 - "extends": "@ljharb",
5 -
6 - "rules": {
7 - "complexity": [2, 20],
8 - "eqeqeq": [2, "allow-null"],
9 - "func-name-matching": [1],
10 - "max-depth": [1, 4],
11 - "max-statements": [2, 26],
12 - "no-extra-parens": [1],
13 - "no-magic-numbers": [0],
14 - "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"],
15 - "sort-keys": [0],
16 - }
17 -}
1 -{
2 - "es3": true,
3 -
4 - "additionalRules": [],
5 -
6 - "requireSemicolons": true,
7 -
8 - "disallowMultipleSpaces": true,
9 -
10 - "disallowIdentifierNames": [],
11 -
12 - "requireCurlyBraces": {
13 - "allExcept": [],
14 - "keywords": ["if", "else", "for", "while", "do", "try", "catch"]
15 - },
16 -
17 - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"],
18 -
19 - "disallowSpaceAfterKeywords": [],
20 -
21 - "disallowSpaceBeforeComma": true,
22 - "disallowSpaceAfterComma": false,
23 - "disallowSpaceBeforeSemicolon": true,
24 -
25 - "disallowNodeTypes": [
26 - "DebuggerStatement",
27 - "LabeledStatement",
28 - "SwitchCase",
29 - "SwitchStatement",
30 - "WithStatement"
31 - ],
32 -
33 - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] },
34 -
35 - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true },
36 - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true },
37 - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true },
38 - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true },
39 - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true },
40 -
41 - "requireSpaceBetweenArguments": true,
42 -
43 - "disallowSpacesInsideParentheses": true,
44 -
45 - "disallowSpacesInsideArrayBrackets": true,
46 -
47 - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] },
48 -
49 - "disallowSpaceAfterObjectKeys": true,
50 -
51 - "requireCommaBeforeLineBreak": true,
52 -
53 - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"],
54 - "requireSpaceAfterPrefixUnaryOperators": [],
55 -
56 - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"],
57 - "requireSpaceBeforePostfixUnaryOperators": [],
58 -
59 - "disallowSpaceBeforeBinaryOperators": [],
60 - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
61 -
62 - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
63 - "disallowSpaceAfterBinaryOperators": [],
64 -
65 - "disallowImplicitTypeConversion": ["binary", "string"],
66 -
67 - "disallowKeywords": ["with", "eval"],
68 -
69 - "requireKeywordsOnNewLine": [],
70 - "disallowKeywordsOnNewLine": ["else"],
71 -
72 - "requireLineFeedAtFileEnd": true,
73 -
74 - "disallowTrailingWhitespace": true,
75 -
76 - "disallowTrailingComma": true,
77 -
78 - "excludeFiles": ["node_modules/**", "vendor/**"],
79 -
80 - "disallowMultipleLineStrings": true,
81 -
82 - "requireDotNotation": { "allExcept": ["keywords"] },
83 -
84 - "requireParenthesesAroundIIFE": true,
85 -
86 - "validateLineBreaks": "LF",
87 -
88 - "validateQuoteMarks": {
89 - "escape": true,
90 - "mark": "'"
91 - },
92 -
93 - "disallowOperatorBeforeLineBreak": [],
94 -
95 - "requireSpaceBeforeKeywords": [
96 - "do",
97 - "for",
98 - "if",
99 - "else",
100 - "switch",
101 - "case",
102 - "try",
103 - "catch",
104 - "finally",
105 - "while",
106 - "with",
107 - "return"
108 - ],
109 -
110 - "validateAlignedFunctionParameters": {
111 - "lineBreakAfterOpeningBraces": true,
112 - "lineBreakBeforeClosingBraces": true
113 - },
114 -
115 - "requirePaddingNewLinesBeforeExport": true,
116 -
117 - "validateNewlineAfterArrayElements": {
118 - "maximum": 6
119 - },
120 -
121 - "requirePaddingNewLinesAfterUseStrict": true,
122 -
123 - "disallowArrowFunctions": true,
124 -
125 - "disallowMultiLineTernary": true,
126 -
127 - "validateOrderInObjectKeys": false,
128 -
129 - "disallowIdenticalDestructuringNames": true,
130 -
131 - "disallowNestedTernaries": { "maxLevel": 1 },
132 -
133 - "requireSpaceAfterComma": { "allExcept": ["trailing"] },
134 - "requireAlignedMultilineParams": false,
135 -
136 - "requireSpacesInGenerator": {
137 - "afterStar": true
138 - },
139 -
140 - "disallowSpacesInGenerator": {
141 - "beforeStar": true
142 - },
143 -
144 - "disallowVar": false,
145 -
146 - "requireArrayDestructuring": false,
147 -
148 - "requireEnhancedObjectLiterals": false,
149 -
150 - "requireObjectDestructuring": false,
151 -
152 - "requireEarlyReturn": false,
153 -
154 - "requireCapitalizedConstructorsNew": {
155 - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"]
156 - },
157 -
158 - "requireImportAlphabetized": false,
159 -
160 - "requireSpaceBeforeObjectValues": true,
161 - "requireSpaceBeforeDestructuredValues": true,
162 -
163 - "disallowSpacesInsideTemplateStringPlaceholders": true,
164 -
165 - "disallowArrayDestructuringReturn": false,
166 -
167 - "requireNewlineBeforeSingleStatementsInIf": false,
168 -
169 - "disallowUnusedVariables": true,
170 -
171 - "requireSpacesInsideImportedObjectBraces": true,
172 -
173 - "requireUseStrict": true
174 -}
175 -
1 -language: node_js
2 -os:
3 - - linux
4 -node_js:
5 - - "10.7"
6 - - "9.11"
7 - - "8.11"
8 - - "7.10"
9 - - "6.14"
10 - - "5.12"
11 - - "4.9"
12 - - "iojs-v3.3"
13 - - "iojs-v2.5"
14 - - "iojs-v1.8"
15 - - "0.12"
16 - - "0.10"
17 - - "0.8"
18 -before_install:
19 - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac'
20 - - 'nvm install-latest-npm'
21 -install:
22 - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;'
23 -script:
24 - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi'
25 - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi'
26 - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi'
27 - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi'
28 -sudo: false
29 -env:
30 - - TEST=true
31 -matrix:
32 - fast_finish: true
33 - include:
34 - - node_js: "lts/*"
35 - env: PRETEST=true
36 - - node_js: "lts/*"
37 - env: POSTTEST=true
38 - - node_js: "4"
39 - env: COVERAGE=true
40 - - node_js: "10.6"
41 - env: TEST=true ALLOW_FAILURE=true
42 - - node_js: "10.5"
43 - env: TEST=true ALLOW_FAILURE=true
44 - - node_js: "10.4"
45 - env: TEST=true ALLOW_FAILURE=true
46 - - node_js: "10.3"
47 - env: TEST=true ALLOW_FAILURE=true
48 - - node_js: "10.2"
49 - env: TEST=true ALLOW_FAILURE=true
50 - - node_js: "10.1"
51 - env: TEST=true ALLOW_FAILURE=true
52 - - node_js: "10.0"
53 - env: TEST=true ALLOW_FAILURE=true
54 - - node_js: "9.10"
55 - env: TEST=true ALLOW_FAILURE=true
56 - - node_js: "9.9"
57 - env: TEST=true ALLOW_FAILURE=true
58 - - node_js: "9.8"
59 - env: TEST=true ALLOW_FAILURE=true
60 - - node_js: "9.7"
61 - env: TEST=true ALLOW_FAILURE=true
62 - - node_js: "9.6"
63 - env: TEST=true ALLOW_FAILURE=true
64 - - node_js: "9.5"
65 - env: TEST=true ALLOW_FAILURE=true
66 - - node_js: "9.4"
67 - env: TEST=true ALLOW_FAILURE=true
68 - - node_js: "9.3"
69 - env: TEST=true ALLOW_FAILURE=true
70 - - node_js: "9.2"
71 - env: TEST=true ALLOW_FAILURE=true
72 - - node_js: "9.1"
73 - env: TEST=true ALLOW_FAILURE=true
74 - - node_js: "9.0"
75 - env: TEST=true ALLOW_FAILURE=true
76 - - node_js: "8.10"
77 - env: TEST=true ALLOW_FAILURE=true
78 - - node_js: "8.9"
79 - env: TEST=true ALLOW_FAILURE=true
80 - - node_js: "8.8"
81 - env: TEST=true ALLOW_FAILURE=true
82 - - node_js: "8.7"
83 - env: TEST=true ALLOW_FAILURE=true
84 - - node_js: "8.6"
85 - env: TEST=true ALLOW_FAILURE=true
86 - - node_js: "8.5"
87 - env: TEST=true ALLOW_FAILURE=true
88 - - node_js: "8.4"
89 - env: TEST=true ALLOW_FAILURE=true
90 - - node_js: "8.3"
91 - env: TEST=true ALLOW_FAILURE=true
92 - - node_js: "8.2"
93 - env: TEST=true ALLOW_FAILURE=true
94 - - node_js: "8.1"
95 - env: TEST=true ALLOW_FAILURE=true
96 - - node_js: "8.0"
97 - env: TEST=true ALLOW_FAILURE=true
98 - - node_js: "7.9"
99 - env: TEST=true ALLOW_FAILURE=true
100 - - node_js: "7.8"
101 - env: TEST=true ALLOW_FAILURE=true
102 - - node_js: "7.7"
103 - env: TEST=true ALLOW_FAILURE=true
104 - - node_js: "7.6"
105 - env: TEST=true ALLOW_FAILURE=true
106 - - node_js: "7.5"
107 - env: TEST=true ALLOW_FAILURE=true
108 - - node_js: "7.4"
109 - env: TEST=true ALLOW_FAILURE=true
110 - - node_js: "7.3"
111 - env: TEST=true ALLOW_FAILURE=true
112 - - node_js: "7.2"
113 - env: TEST=true ALLOW_FAILURE=true
114 - - node_js: "7.1"
115 - env: TEST=true ALLOW_FAILURE=true
116 - - node_js: "7.0"
117 - env: TEST=true ALLOW_FAILURE=true
118 - - node_js: "6.13"
119 - env: TEST=true ALLOW_FAILURE=true
120 - - node_js: "6.12"
121 - env: TEST=true ALLOW_FAILURE=true
122 - - node_js: "6.11"
123 - env: TEST=true ALLOW_FAILURE=true
124 - - node_js: "6.10"
125 - env: TEST=true ALLOW_FAILURE=true
126 - - node_js: "6.9"
127 - env: TEST=true ALLOW_FAILURE=true
128 - - node_js: "6.8"
129 - env: TEST=true ALLOW_FAILURE=true
130 - - node_js: "6.7"
131 - env: TEST=true ALLOW_FAILURE=true
132 - - node_js: "6.6"
133 - env: TEST=true ALLOW_FAILURE=true
134 - - node_js: "6.5"
135 - env: TEST=true ALLOW_FAILURE=true
136 - - node_js: "6.4"
137 - env: TEST=true ALLOW_FAILURE=true
138 - - node_js: "6.3"
139 - env: TEST=true ALLOW_FAILURE=true
140 - - node_js: "6.2"
141 - env: TEST=true ALLOW_FAILURE=true
142 - - node_js: "6.1"
143 - env: TEST=true ALLOW_FAILURE=true
144 - - node_js: "6.0"
145 - env: TEST=true ALLOW_FAILURE=true
146 - - node_js: "5.11"
147 - env: TEST=true ALLOW_FAILURE=true
148 - - node_js: "5.10"
149 - env: TEST=true ALLOW_FAILURE=true
150 - - node_js: "5.9"
151 - env: TEST=true ALLOW_FAILURE=true
152 - - node_js: "5.8"
153 - env: TEST=true ALLOW_FAILURE=true
154 - - node_js: "5.7"
155 - env: TEST=true ALLOW_FAILURE=true
156 - - node_js: "5.6"
157 - env: TEST=true ALLOW_FAILURE=true
158 - - node_js: "5.5"
159 - env: TEST=true ALLOW_FAILURE=true
160 - - node_js: "5.4"
161 - env: TEST=true ALLOW_FAILURE=true
162 - - node_js: "5.3"
163 - env: TEST=true ALLOW_FAILURE=true
164 - - node_js: "5.2"
165 - env: TEST=true ALLOW_FAILURE=true
166 - - node_js: "5.1"
167 - env: TEST=true ALLOW_FAILURE=true
168 - - node_js: "5.0"
169 - env: TEST=true ALLOW_FAILURE=true
170 - - node_js: "4.8"
171 - env: TEST=true ALLOW_FAILURE=true
172 - - node_js: "4.7"
173 - env: TEST=true ALLOW_FAILURE=true
174 - - node_js: "4.6"
175 - env: TEST=true ALLOW_FAILURE=true
176 - - node_js: "4.5"
177 - env: TEST=true ALLOW_FAILURE=true
178 - - node_js: "4.4"
179 - env: TEST=true ALLOW_FAILURE=true
180 - - node_js: "4.3"
181 - env: TEST=true ALLOW_FAILURE=true
182 - - node_js: "4.2"
183 - env: TEST=true ALLOW_FAILURE=true
184 - - node_js: "4.1"
185 - env: TEST=true ALLOW_FAILURE=true
186 - - node_js: "4.0"
187 - env: TEST=true ALLOW_FAILURE=true
188 - - node_js: "iojs-v3.2"
189 - env: TEST=true ALLOW_FAILURE=true
190 - - node_js: "iojs-v3.1"
191 - env: TEST=true ALLOW_FAILURE=true
192 - - node_js: "iojs-v3.0"
193 - env: TEST=true ALLOW_FAILURE=true
194 - - node_js: "iojs-v2.4"
195 - env: TEST=true ALLOW_FAILURE=true
196 - - node_js: "iojs-v2.3"
197 - env: TEST=true ALLOW_FAILURE=true
198 - - node_js: "iojs-v2.2"
199 - env: TEST=true ALLOW_FAILURE=true
200 - - node_js: "iojs-v2.1"
201 - env: TEST=true ALLOW_FAILURE=true
202 - - node_js: "iojs-v2.0"
203 - env: TEST=true ALLOW_FAILURE=true
204 - - node_js: "iojs-v1.7"
205 - env: TEST=true ALLOW_FAILURE=true
206 - - node_js: "iojs-v1.6"
207 - env: TEST=true ALLOW_FAILURE=true
208 - - node_js: "iojs-v1.5"
209 - env: TEST=true ALLOW_FAILURE=true
210 - - node_js: "iojs-v1.4"
211 - env: TEST=true ALLOW_FAILURE=true
212 - - node_js: "iojs-v1.3"
213 - env: TEST=true ALLOW_FAILURE=true
214 - - node_js: "iojs-v1.2"
215 - env: TEST=true ALLOW_FAILURE=true
216 - - node_js: "iojs-v1.1"
217 - env: TEST=true ALLOW_FAILURE=true
218 - - node_js: "iojs-v1.0"
219 - env: TEST=true ALLOW_FAILURE=true
220 - - node_js: "0.11"
221 - env: TEST=true ALLOW_FAILURE=true
222 - - node_js: "0.9"
223 - env: TEST=true ALLOW_FAILURE=true
224 - - node_js: "0.6"
225 - env: TEST=true ALLOW_FAILURE=true
226 - - node_js: "0.4"
227 - env: TEST=true ALLOW_FAILURE=true
228 - allow_failures:
229 - - os: osx
230 - - env: TEST=true ALLOW_FAILURE=true
1 -3.0.2 / 2018-07-19
2 -==================
3 - * [Fix] Prevent merging `__proto__` property (#48)
4 - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`
5 - * [Tests] up to `node` `v10.7`, `v9.11`, `v8.11`, `v7.10`, `v6.14`, `v4.9`; use `nvm install-latest-npm`
6 -
7 -3.0.1 / 2017-04-27
8 -==================
9 - * [Fix] deep extending should work with a non-object (#46)
10 - * [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`
11 - * [Tests] up to `node` `v7.9`, `v6.10`, `v4.8`; improve matrix
12 - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG.
13 - * [Docs] Add example to readme (#34)
14 -
15 -3.0.0 / 2015-07-01
16 -==================
17 - * [Possible breaking change] Use global "strict" directive (#32)
18 - * [Tests] `int` is an ES3 reserved word
19 - * [Tests] Test up to `io.js` `v2.3`
20 - * [Tests] Add `npm run eslint`
21 - * [Dev Deps] Update `covert`, `jscs`
22 -
23 -2.0.1 / 2015-04-25
24 -==================
25 - * Use an inline `isArray` check, for ES3 browsers. (#27)
26 - * Some old browsers fail when an identifier is `toString`
27 - * Test latest `node` and `io.js` versions on `travis-ci`; speed up builds
28 - * Add license info to package.json (#25)
29 - * Update `tape`, `jscs`
30 - * Adding a CHANGELOG
31 -
32 -2.0.0 / 2014-10-01
33 -==================
34 - * Increase code coverage to 100%; run code coverage as part of tests
35 - * Add `npm run lint`; Run linter as part of tests
36 - * Remove nodeType and setInterval checks in isPlainObject
37 - * Updating `tape`, `jscs`, `covert`
38 - * General style and README cleanup
39 -
40 -1.3.0 / 2014-06-20
41 -==================
42 - * Add component.json for browser support (#18)
43 - * Use SVG for badges in README (#16)
44 - * Updating `tape`, `covert`
45 - * Updating travis-ci to work with multiple node versions
46 - * Fix `deep === false` bug (returning target as {}) (#14)
47 - * Fixing constructor checks in isPlainObject
48 - * Adding additional test coverage
49 - * Adding `npm run coverage`
50 - * Add LICENSE (#13)
51 - * Adding a warning about `false`, per #11
52 - * General style and whitespace cleanup
53 -
54 -1.2.1 / 2013-09-14
55 -==================
56 - * Fixing hasOwnProperty bugs that would only have shown up in specific browsers. Fixes #8
57 - * Updating `tape`
58 -
59 -1.2.0 / 2013-09-02
60 -==================
61 - * Updating the README: add badges
62 - * Adding a missing variable reference.
63 - * Using `tape` instead of `buster` for tests; add more tests (#7)
64 - * Adding node 0.10 to Travis CI (#6)
65 - * Enabling "npm test" and cleaning up package.json (#5)
66 - * Add Travis CI.
67 -
68 -1.1.3 / 2012-12-06
69 -==================
70 - * Added unit tests.
71 - * Ensure extend function is named. (Looks nicer in a stack trace.)
72 - * README cleanup.
73 -
74 -1.1.1 / 2012-11-07
75 -==================
76 - * README cleanup.
77 - * Added installation instructions.
78 - * Added a missing semicolon
79 -
80 -1.0.0 / 2012-04-08
81 -==================
82 - * Initial commit
83 -
1 -The MIT License (MIT)
2 -
3 -Copyright (c) 2014 Stefan Thomas
4 -
5 -Permission is hereby granted, free of charge, to any person obtaining
6 -a copy of this software and associated documentation files (the
7 -"Software"), to deal in the Software without restriction, including
8 -without limitation the rights to use, copy, modify, merge, publish,
9 -distribute, sublicense, and/or sell copies of the Software, and to
10 -permit persons to whom the Software is furnished to do so, subject to
11 -the following conditions:
12 -
13 -The above copyright notice and this permission notice shall be
14 -included in all copies or substantial portions of the Software.
15 -
16 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 -
1 -[![Build Status][travis-svg]][travis-url]
2 -[![dependency status][deps-svg]][deps-url]
3 -[![dev dependency status][dev-deps-svg]][dev-deps-url]
4 -
5 -# extend() for Node.js <sup>[![Version Badge][npm-version-png]][npm-url]</sup>
6 -
7 -`node-extend` is a port of the classic extend() method from jQuery. It behaves as you expect. It is simple, tried and true.
8 -
9 -Notes:
10 -
11 -* Since Node.js >= 4,
12 - [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
13 - now offers the same functionality natively (but without the "deep copy" option).
14 - See [ECMAScript 2015 (ES6) in Node.js](https://nodejs.org/en/docs/es6).
15 -* Some native implementations of `Object.assign` in both Node.js and many
16 - browsers (since NPM modules are for the browser too) may not be fully
17 - spec-compliant.
18 - Check [`object.assign`](https://www.npmjs.com/package/object.assign) module for
19 - a compliant candidate.
20 -
21 -## Installation
22 -
23 -This package is available on [npm][npm-url] as: `extend`
24 -
25 -``` sh
26 -npm install extend
27 -```
28 -
29 -## Usage
30 -
31 -**Syntax:** extend **(** [`deep`], `target`, `object1`, [`objectN`] **)**
32 -
33 -*Extend one object with one or more others, returning the modified object.*
34 -
35 -**Example:**
36 -
37 -``` js
38 -var extend = require('extend');
39 -extend(targetObject, object1, object2);
40 -```
41 -
42 -Keep in mind that the target object will be modified, and will be returned from extend().
43 -
44 -If a boolean true is specified as the first argument, extend performs a deep copy, recursively copying any objects it finds. Otherwise, the copy will share structure with the original object(s).
45 -Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over.
46 -Warning: passing `false` as the first argument is not supported.
47 -
48 -### Arguments
49 -
50 -* `deep` *Boolean* (optional)
51 -If set, the merge becomes recursive (i.e. deep copy).
52 -* `target` *Object*
53 -The object to extend.
54 -* `object1` *Object*
55 -The object that will be merged into the first.
56 -* `objectN` *Object* (Optional)
57 -More objects to merge into the first.
58 -
59 -## License
60 -
61 -`node-extend` is licensed under the [MIT License][mit-license-url].
62 -
63 -## Acknowledgements
64 -
65 -All credit to the jQuery authors for perfecting this amazing utility.
66 -
67 -Ported to Node.js by [Stefan Thomas][github-justmoon] with contributions by [Jonathan Buchanan][github-insin] and [Jordan Harband][github-ljharb].
68 -
69 -[travis-svg]: https://travis-ci.org/justmoon/node-extend.svg
70 -[travis-url]: https://travis-ci.org/justmoon/node-extend
71 -[npm-url]: https://npmjs.org/package/extend
72 -[mit-license-url]: http://opensource.org/licenses/MIT
73 -[github-justmoon]: https://github.com/justmoon
74 -[github-insin]: https://github.com/insin
75 -[github-ljharb]: https://github.com/ljharb
76 -[npm-version-png]: http://versionbadg.es/justmoon/node-extend.svg
77 -[deps-svg]: https://david-dm.org/justmoon/node-extend.svg
78 -[deps-url]: https://david-dm.org/justmoon/node-extend
79 -[dev-deps-svg]: https://david-dm.org/justmoon/node-extend/dev-status.svg
80 -[dev-deps-url]: https://david-dm.org/justmoon/node-extend#info=devDependencies
81 -
1 -{
2 - "name": "extend",
3 - "author": "Stefan Thomas <justmoon@members.fsf.org> (http://www.justmoon.net)",
4 - "version": "3.0.0",
5 - "description": "Port of jQuery.extend for node.js and the browser.",
6 - "scripts": [
7 - "index.js"
8 - ],
9 - "contributors": [
10 - {
11 - "name": "Jordan Harband",
12 - "url": "https://github.com/ljharb"
13 - }
14 - ],
15 - "keywords": [
16 - "extend",
17 - "clone",
18 - "merge"
19 - ],
20 - "repository" : {
21 - "type": "git",
22 - "url": "https://github.com/justmoon/node-extend.git"
23 - },
24 - "dependencies": {
25 - },
26 - "devDependencies": {
27 - "tape" : "~3.0.0",
28 - "covert": "~0.4.0",
29 - "jscs": "~1.6.2"
30 - }
31 -}
32 -
1 -'use strict';
2 -
3 -var hasOwn = Object.prototype.hasOwnProperty;
4 -var toStr = Object.prototype.toString;
5 -var defineProperty = Object.defineProperty;
6 -var gOPD = Object.getOwnPropertyDescriptor;
7 -
8 -var isArray = function isArray(arr) {
9 - if (typeof Array.isArray === 'function') {
10 - return Array.isArray(arr);
11 - }
12 -
13 - return toStr.call(arr) === '[object Array]';
14 -};
15 -
16 -var isPlainObject = function isPlainObject(obj) {
17 - if (!obj || toStr.call(obj) !== '[object Object]') {
18 - return false;
19 - }
20 -
21 - var hasOwnConstructor = hasOwn.call(obj, 'constructor');
22 - var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
23 - // Not own constructor property must be Object
24 - if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
25 - return false;
26 - }
27 -
28 - // Own properties are enumerated firstly, so to speed up,
29 - // if last one is own, then all properties are own.
30 - var key;
31 - for (key in obj) { /**/ }
32 -
33 - return typeof key === 'undefined' || hasOwn.call(obj, key);
34 -};
35 -
36 -// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
37 -var setProperty = function setProperty(target, options) {
38 - if (defineProperty && options.name === '__proto__') {
39 - defineProperty(target, options.name, {
40 - enumerable: true,
41 - configurable: true,
42 - value: options.newValue,
43 - writable: true
44 - });
45 - } else {
46 - target[options.name] = options.newValue;
47 - }
48 -};
49 -
50 -// Return undefined instead of __proto__ if '__proto__' is not an own property
51 -var getProperty = function getProperty(obj, name) {
52 - if (name === '__proto__') {
53 - if (!hasOwn.call(obj, name)) {
54 - return void 0;
55 - } else if (gOPD) {
56 - // In early versions of node, obj['__proto__'] is buggy when obj has
57 - // __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
58 - return gOPD(obj, name).value;
59 - }
60 - }
61 -
62 - return obj[name];
63 -};
64 -
65 -module.exports = function extend() {
66 - var options, name, src, copy, copyIsArray, clone;
67 - var target = arguments[0];
68 - var i = 1;
69 - var length = arguments.length;
70 - var deep = false;
71 -
72 - // Handle a deep copy situation
73 - if (typeof target === 'boolean') {
74 - deep = target;
75 - target = arguments[1] || {};
76 - // skip the boolean and the target
77 - i = 2;
78 - }
79 - if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
80 - target = {};
81 - }
82 -
83 - for (; i < length; ++i) {
84 - options = arguments[i];
85 - // Only deal with non-null/undefined values
86 - if (options != null) {
87 - // Extend the base object
88 - for (name in options) {
89 - src = getProperty(target, name);
90 - copy = getProperty(options, name);
91 -
92 - // Prevent never-ending loop
93 - if (target !== copy) {
94 - // Recurse if we're merging plain objects or arrays
95 - if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
96 - if (copyIsArray) {
97 - copyIsArray = false;
98 - clone = src && isArray(src) ? src : [];
99 - } else {
100 - clone = src && isPlainObject(src) ? src : {};
101 - }
102 -
103 - // Never move original objects, clone them
104 - setProperty(target, { name: name, newValue: extend(deep, clone, copy) });
105 -
106 - // Don't bring in undefined values
107 - } else if (typeof copy !== 'undefined') {
108 - setProperty(target, { name: name, newValue: copy });
109 - }
110 - }
111 - }
112 - }
113 - }
114 -
115 - // Return the modified object
116 - return target;
117 -};
1 -{
2 - "name": "extend",
3 - "author": "Stefan Thomas <justmoon@members.fsf.org> (http://www.justmoon.net)",
4 - "version": "3.0.2",
5 - "description": "Port of jQuery.extend for node.js and the browser",
6 - "main": "index",
7 - "scripts": {
8 - "pretest": "npm run lint",
9 - "test": "npm run tests-only",
10 - "posttest": "npm run coverage-quiet",
11 - "tests-only": "node test",
12 - "coverage": "covert test/index.js",
13 - "coverage-quiet": "covert test/index.js --quiet",
14 - "lint": "npm run jscs && npm run eslint",
15 - "jscs": "jscs *.js */*.js",
16 - "eslint": "eslint *.js */*.js"
17 - },
18 - "contributors": [
19 - {
20 - "name": "Jordan Harband",
21 - "url": "https://github.com/ljharb"
22 - }
23 - ],
24 - "keywords": [
25 - "extend",
26 - "clone",
27 - "merge"
28 - ],
29 - "repository": {
30 - "type": "git",
31 - "url": "https://github.com/justmoon/node-extend.git"
32 - },
33 - "dependencies": {},
34 - "devDependencies": {
35 - "@ljharb/eslint-config": "^12.2.1",
36 - "covert": "^1.1.0",
37 - "eslint": "^4.19.1",
38 - "jscs": "^3.0.7",
39 - "tape": "^4.9.1"
40 - },
41 - "license": "MIT"
42 -}
1 -Copyright (c) 2012, Joyent, Inc. All rights reserved.
2 -
3 -Permission is hereby granted, free of charge, to any person obtaining a copy
4 -of this software and associated documentation files (the "Software"), to deal
5 -in the Software without restriction, including without limitation the rights
6 -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 -copies of the Software, and to permit persons to whom the Software is
8 -furnished to do so, subject to the following conditions:
9 -
10 -The above copyright notice and this permission notice shall be included in
11 -all copies or substantial portions of the Software.
12 -
13 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 -THE SOFTWARE
1 -#
2 -# Copyright (c) 2012, Joyent, Inc. All rights reserved.
3 -#
4 -# Makefile: top-level Makefile
5 -#
6 -# This Makefile contains only repo-specific logic and uses included makefiles
7 -# to supply common targets (javascriptlint, jsstyle, restdown, etc.), which are
8 -# used by other repos as well.
9 -#
10 -
11 -#
12 -# Files
13 -#
14 -JSL = jsl
15 -JSSTYLE = jsstyle
16 -JS_FILES := $(shell find examples lib -name '*.js')
17 -JSL_FILES_NODE = $(JS_FILES)
18 -JSSTYLE_FILES = $(JS_FILES)
19 -JSL_CONF_NODE = jsl.node.conf
20 -
21 -# Default target is "check"
22 -check:
23 -
24 -include ./Makefile.targ
1 -# -*- mode: makefile -*-
2 -#
3 -# Copyright (c) 2012, Joyent, Inc. All rights reserved.
4 -#
5 -# Makefile.targ: common targets.
6 -#
7 -# NOTE: This makefile comes from the "eng" repo. It's designed to be dropped
8 -# into other repos as-is without requiring any modifications. If you find
9 -# yourself changing this file, you should instead update the original copy in
10 -# eng.git and then update your repo to use the new version.
11 -#
12 -# This Makefile defines several useful targets and rules. You can use it by
13 -# including it from a Makefile that specifies some of the variables below.
14 -#
15 -# Targets defined in this Makefile:
16 -#
17 -# check Checks JavaScript files for lint and style
18 -# Checks bash scripts for syntax
19 -# Checks SMF manifests for validity against the SMF DTD
20 -#
21 -# clean Removes built files
22 -#
23 -# docs Builds restdown documentation in docs/
24 -#
25 -# prepush Depends on "check" and "test"
26 -#
27 -# test Does nothing (you should override this)
28 -#
29 -# xref Generates cscope (source cross-reference index)
30 -#
31 -# For details on what these targets are supposed to do, see the Joyent
32 -# Engineering Guide.
33 -#
34 -# To make use of these targets, you'll need to set some of these variables. Any
35 -# variables left unset will simply not be used.
36 -#
37 -# BASH_FILES Bash scripts to check for syntax
38 -# (paths relative to top-level Makefile)
39 -#
40 -# CLEAN_FILES Files to remove as part of the "clean" target. Note
41 -# that files generated by targets in this Makefile are
42 -# automatically included in CLEAN_FILES. These include
43 -# restdown-generated HTML and JSON files.
44 -#
45 -# DOC_FILES Restdown (documentation source) files. These are
46 -# assumed to be contained in "docs/", and must NOT
47 -# contain the "docs/" prefix.
48 -#
49 -# JSL_CONF_NODE Specify JavaScriptLint configuration files
50 -# JSL_CONF_WEB (paths relative to top-level Makefile)
51 -#
52 -# Node.js and Web configuration files are separate
53 -# because you'll usually want different global variable
54 -# configurations. If no file is specified, none is given
55 -# to jsl, which causes it to use a default configuration,
56 -# which probably isn't what you want.
57 -#
58 -# JSL_FILES_NODE JavaScript files to check with Node config file.
59 -# JSL_FILES_WEB JavaScript files to check with Web config file.
60 -#
61 -# You can also override these variables:
62 -#
63 -# BASH Path to bash (default: bash)
64 -#
65 -# CSCOPE_DIRS Directories to search for source files for the cscope
66 -# index. (default: ".")
67 -#
68 -# JSL Path to JavaScriptLint (default: "jsl")
69 -#
70 -# JSL_FLAGS_NODE Additional flags to pass through to JSL
71 -# JSL_FLAGS_WEB
72 -# JSL_FLAGS
73 -#
74 -# JSSTYLE Path to jsstyle (default: jsstyle)
75 -#
76 -# JSSTYLE_FLAGS Additional flags to pass through to jsstyle
77 -#
78 -
79 -#
80 -# Defaults for the various tools we use.
81 -#
82 -BASH ?= bash
83 -BASHSTYLE ?= tools/bashstyle
84 -CP ?= cp
85 -CSCOPE ?= cscope
86 -CSCOPE_DIRS ?= .
87 -JSL ?= jsl
88 -JSSTYLE ?= jsstyle
89 -MKDIR ?= mkdir -p
90 -MV ?= mv
91 -RESTDOWN_FLAGS ?=
92 -RMTREE ?= rm -rf
93 -JSL_FLAGS ?= --nologo --nosummary
94 -
95 -ifeq ($(shell uname -s),SunOS)
96 - TAR ?= gtar
97 -else
98 - TAR ?= tar
99 -endif
100 -
101 -
102 -#
103 -# Defaults for other fixed values.
104 -#
105 -BUILD = build
106 -DISTCLEAN_FILES += $(BUILD)
107 -DOC_BUILD = $(BUILD)/docs/public
108 -
109 -#
110 -# Configure JSL_FLAGS_{NODE,WEB} based on JSL_CONF_{NODE,WEB}.
111 -#
112 -ifneq ($(origin JSL_CONF_NODE), undefined)
113 - JSL_FLAGS_NODE += --conf=$(JSL_CONF_NODE)
114 -endif
115 -
116 -ifneq ($(origin JSL_CONF_WEB), undefined)
117 - JSL_FLAGS_WEB += --conf=$(JSL_CONF_WEB)
118 -endif
119 -
120 -#
121 -# Targets. For descriptions on what these are supposed to do, see the
122 -# Joyent Engineering Guide.
123 -#
124 -
125 -#
126 -# Instruct make to keep around temporary files. We have rules below that
127 -# automatically update git submodules as needed, but they employ a deps/*/.git
128 -# temporary file. Without this directive, make tries to remove these .git
129 -# directories after the build has completed.
130 -#
131 -.SECONDARY: $($(wildcard deps/*):%=%/.git)
132 -
133 -#
134 -# This rule enables other rules that use files from a git submodule to have
135 -# those files depend on deps/module/.git and have "make" automatically check
136 -# out the submodule as needed.
137 -#
138 -deps/%/.git:
139 - git submodule update --init deps/$*
140 -
141 -#
142 -# These recipes make heavy use of dynamically-created phony targets. The parent
143 -# Makefile defines a list of input files like BASH_FILES. We then say that each
144 -# of these files depends on a fake target called filename.bashchk, and then we
145 -# define a pattern rule for those targets that runs bash in check-syntax-only
146 -# mode. This mechanism has the nice properties that if you specify zero files,
147 -# the rule becomes a noop (unlike a single rule to check all bash files, which
148 -# would invoke bash with zero files), and you can check individual files from
149 -# the command line with "make filename.bashchk".
150 -#
151 -.PHONY: check-bash
152 -check-bash: $(BASH_FILES:%=%.bashchk) $(BASH_FILES:%=%.bashstyle)
153 -
154 -%.bashchk: %
155 - $(BASH) -n $^
156 -
157 -%.bashstyle: %
158 - $(BASHSTYLE) $^
159 -
160 -.PHONY: check-jsl check-jsl-node check-jsl-web
161 -check-jsl: check-jsl-node check-jsl-web
162 -
163 -check-jsl-node: $(JSL_FILES_NODE:%=%.jslnodechk)
164 -
165 -check-jsl-web: $(JSL_FILES_WEB:%=%.jslwebchk)
166 -
167 -%.jslnodechk: % $(JSL_EXEC)
168 - $(JSL) $(JSL_FLAGS) $(JSL_FLAGS_NODE) $<
169 -
170 -%.jslwebchk: % $(JSL_EXEC)
171 - $(JSL) $(JSL_FLAGS) $(JSL_FLAGS_WEB) $<
172 -
173 -.PHONY: check-jsstyle
174 -check-jsstyle: $(JSSTYLE_FILES:%=%.jsstylechk)
175 -
176 -%.jsstylechk: % $(JSSTYLE_EXEC)
177 - $(JSSTYLE) $(JSSTYLE_FLAGS) $<
178 -
179 -.PHONY: check
180 -check: check-jsl check-jsstyle check-bash
181 - @echo check ok
182 -
183 -.PHONY: clean
184 -clean::
185 - -$(RMTREE) $(CLEAN_FILES)
186 -
187 -.PHONY: distclean
188 -distclean:: clean
189 - -$(RMTREE) $(DISTCLEAN_FILES)
190 -
191 -CSCOPE_FILES = cscope.in.out cscope.out cscope.po.out
192 -CLEAN_FILES += $(CSCOPE_FILES)
193 -
194 -.PHONY: xref
195 -xref: cscope.files
196 - $(CSCOPE) -bqR
197 -
198 -.PHONY: cscope.files
199 -cscope.files:
200 - find $(CSCOPE_DIRS) -name '*.c' -o -name '*.h' -o -name '*.cc' \
201 - -o -name '*.js' -o -name '*.s' -o -name '*.cpp' > $@
202 -
203 -#
204 -# The "docs" target is complicated because we do several things here:
205 -#
206 -# (1) Use restdown to build HTML and JSON files from each of DOC_FILES.
207 -#
208 -# (2) Copy these files into $(DOC_BUILD) (build/docs/public), which
209 -# functions as a complete copy of the documentation that could be
210 -# mirrored or served over HTTP.
211 -#
212 -# (3) Then copy any directories and media from docs/media into
213 -# $(DOC_BUILD)/media. This allows projects to include their own media,
214 -# including files that will override same-named files provided by
215 -# restdown.
216 -#
217 -# Step (3) is the surprisingly complex part: in order to do this, we need to
218 -# identify the subdirectories in docs/media, recreate them in
219 -# $(DOC_BUILD)/media, then do the same with the files.
220 -#
221 -DOC_MEDIA_DIRS := $(shell find docs/media -type d 2>/dev/null | grep -v "^docs/media$$")
222 -DOC_MEDIA_DIRS := $(DOC_MEDIA_DIRS:docs/media/%=%)
223 -DOC_MEDIA_DIRS_BUILD := $(DOC_MEDIA_DIRS:%=$(DOC_BUILD)/media/%)
224 -
225 -DOC_MEDIA_FILES := $(shell find docs/media -type f 2>/dev/null)
226 -DOC_MEDIA_FILES := $(DOC_MEDIA_FILES:docs/media/%=%)
227 -DOC_MEDIA_FILES_BUILD := $(DOC_MEDIA_FILES:%=$(DOC_BUILD)/media/%)
228 -
229 -#
230 -# Like the other targets, "docs" just depends on the final files we want to
231 -# create in $(DOC_BUILD), leveraging other targets and recipes to define how
232 -# to get there.
233 -#
234 -.PHONY: docs
235 -docs: \
236 - $(DOC_FILES:%.restdown=$(DOC_BUILD)/%.html) \
237 - $(DOC_FILES:%.restdown=$(DOC_BUILD)/%.json) \
238 - $(DOC_MEDIA_FILES_BUILD)
239 -
240 -#
241 -# We keep the intermediate files so that the next build can see whether the
242 -# files in DOC_BUILD are up to date.
243 -#
244 -.PRECIOUS: \
245 - $(DOC_FILES:%.restdown=docs/%.html) \
246 - $(DOC_FILES:%.restdown=docs/%json)
247 -
248 -#
249 -# We do clean those intermediate files, as well as all of DOC_BUILD.
250 -#
251 -CLEAN_FILES += \
252 - $(DOC_BUILD) \
253 - $(DOC_FILES:%.restdown=docs/%.html) \
254 - $(DOC_FILES:%.restdown=docs/%.json)
255 -
256 -#
257 -# Before installing the files, we must make sure the directories exist. The |
258 -# syntax tells make that the dependency need only exist, not be up to date.
259 -# Otherwise, it might try to rebuild spuriously because the directory itself
260 -# appears out of date.
261 -#
262 -$(DOC_MEDIA_FILES_BUILD): | $(DOC_MEDIA_DIRS_BUILD)
263 -
264 -$(DOC_BUILD)/%: docs/% | $(DOC_BUILD)
265 - $(CP) $< $@
266 -
267 -docs/%.json docs/%.html: docs/%.restdown | $(DOC_BUILD) $(RESTDOWN_EXEC)
268 - $(RESTDOWN) $(RESTDOWN_FLAGS) -m $(DOC_BUILD) $<
269 -
270 -$(DOC_BUILD):
271 - $(MKDIR) $@
272 -
273 -$(DOC_MEDIA_DIRS_BUILD):
274 - $(MKDIR) $@
275 -
276 -#
277 -# The default "test" target does nothing. This should usually be overridden by
278 -# the parent Makefile. It's included here so we can define "prepush" without
279 -# requiring the repo to define "test".
280 -#
281 -.PHONY: test
282 -test:
283 -
284 -.PHONY: prepush
285 -prepush: check test
1 -# extsprintf: extended POSIX-style sprintf
2 -
3 -Stripped down version of s[n]printf(3c). We make a best effort to throw an
4 -exception when given a format string we don't understand, rather than ignoring
5 -it, so that we won't break existing programs if/when we go implement the rest
6 -of this.
7 -
8 -This implementation currently supports specifying
9 -
10 -* field alignment ('-' flag),
11 -* zero-pad ('0' flag)
12 -* always show numeric sign ('+' flag),
13 -* field width
14 -* conversions for strings, decimal integers, and floats (numbers).
15 -* argument size specifiers. These are all accepted but ignored, since
16 - Javascript has no notion of the physical size of an argument.
17 -
18 -Everything else is currently unsupported, most notably: precision, unsigned
19 -numbers, non-decimal numbers, and characters.
20 -
21 -Besides the usual POSIX conversions, this implementation supports:
22 -
23 -* `%j`: pretty-print a JSON object (using node's "inspect")
24 -* `%r`: pretty-print an Error object
25 -
26 -# Example
27 -
28 -First, install it:
29 -
30 - # npm install extsprintf
31 -
32 -Now, use it:
33 -
34 - var mod_extsprintf = require('extsprintf');
35 - console.log(mod_extsprintf.sprintf('hello %25s', 'world'));
36 -
37 -outputs:
38 -
39 - hello world
40 -
41 -# Also supported
42 -
43 -**printf**: same args as sprintf, but prints the result to stdout
44 -
45 -**fprintf**: same args as sprintf, preceded by a Node stream. Prints the result
46 -to the given stream.
1 -#
2 -# Configuration File for JavaScript Lint
3 -#
4 -# This configuration file can be used to lint a collection of scripts, or to enable
5 -# or disable warnings for scripts that are linted via the command line.
6 -#
7 -
8 -### Warnings
9 -# Enable or disable warnings based on requirements.
10 -# Use "+WarningName" to display or "-WarningName" to suppress.
11 -#
12 -+ambiguous_else_stmt # the else statement could be matched with one of multiple if statements (use curly braces to indicate intent
13 -+ambiguous_nested_stmt # block statements containing block statements should use curly braces to resolve ambiguity
14 -+ambiguous_newline # unexpected end of line; it is ambiguous whether these lines are part of the same statement
15 -+anon_no_return_value # anonymous function does not always return value
16 -+assign_to_function_call # assignment to a function call
17 --block_without_braces # block statement without curly braces
18 -+comma_separated_stmts # multiple statements separated by commas (use semicolons?)
19 -+comparison_type_conv # comparisons against null, 0, true, false, or an empty string allowing implicit type conversion (use === or !==)
20 -+default_not_at_end # the default case is not at the end of the switch statement
21 -+dup_option_explicit # duplicate "option explicit" control comment
22 -+duplicate_case_in_switch # duplicate case in switch statement
23 -+duplicate_formal # duplicate formal argument {name}
24 -+empty_statement # empty statement or extra semicolon
25 -+identifier_hides_another # identifer {name} hides an identifier in a parent scope
26 --inc_dec_within_stmt # increment (++) and decrement (--) operators used as part of greater statement
27 -+incorrect_version # Expected /*jsl:content-type*/ control comment. The script was parsed with the wrong version.
28 -+invalid_fallthru # unexpected "fallthru" control comment
29 -+invalid_pass # unexpected "pass" control comment
30 -+jsl_cc_not_understood # couldn't understand control comment using /*jsl:keyword*/ syntax
31 -+leading_decimal_point # leading decimal point may indicate a number or an object member
32 -+legacy_cc_not_understood # couldn't understand control comment using /*@keyword@*/ syntax
33 -+meaningless_block # meaningless block; curly braces have no impact
34 -+mismatch_ctrl_comments # mismatched control comment; "ignore" and "end" control comments must have a one-to-one correspondence
35 -+misplaced_regex # regular expressions should be preceded by a left parenthesis, assignment, colon, or comma
36 -+missing_break # missing break statement
37 -+missing_break_for_last_case # missing break statement for last case in switch
38 -+missing_default_case # missing default case in switch statement
39 -+missing_option_explicit # the "option explicit" control comment is missing
40 -+missing_semicolon # missing semicolon
41 -+missing_semicolon_for_lambda # missing semicolon for lambda assignment
42 -+multiple_plus_minus # unknown order of operations for successive plus (e.g. x+++y) or minus (e.g. x---y) signs
43 -+nested_comment # nested comment
44 -+no_return_value # function {name} does not always return a value
45 -+octal_number # leading zeros make an octal number
46 -+parseint_missing_radix # parseInt missing radix parameter
47 -+partial_option_explicit # the "option explicit" control comment, if used, must be in the first script tag
48 -+redeclared_var # redeclaration of {name}
49 -+trailing_comma_in_array # extra comma is not recommended in array initializers
50 -+trailing_decimal_point # trailing decimal point may indicate a number or an object member
51 -+undeclared_identifier # undeclared identifier: {name}
52 -+unreachable_code # unreachable code
53 --unreferenced_argument # argument declared but never referenced: {name}
54 --unreferenced_function # function is declared but never referenced: {name}
55 -+unreferenced_variable # variable is declared but never referenced: {name}
56 -+unsupported_version # JavaScript {version} is not supported
57 -+use_of_label # use of label
58 -+useless_assign # useless assignment
59 -+useless_comparison # useless comparison; comparing identical expressions
60 --useless_quotes # the quotation marks are unnecessary
61 -+useless_void # use of the void type may be unnecessary (void is always undefined)
62 -+var_hides_arg # variable {name} hides argument
63 -+want_assign_or_call # expected an assignment or function call
64 -+with_statement # with statement hides undeclared variables; use temporary variable instead
65 -
66 -
67 -### Output format
68 -# Customize the format of the error message.
69 -# __FILE__ indicates current file path
70 -# __FILENAME__ indicates current file name
71 -# __LINE__ indicates current line
72 -# __COL__ indicates current column
73 -# __ERROR__ indicates error message (__ERROR_PREFIX__: __ERROR_MSG__)
74 -# __ERROR_NAME__ indicates error name (used in configuration file)
75 -# __ERROR_PREFIX__ indicates error prefix
76 -# __ERROR_MSG__ indicates error message
77 -#
78 -# For machine-friendly output, the output format can be prefixed with
79 -# "encode:". If specified, all items will be encoded with C-slashes.
80 -#
81 -# Visual Studio syntax (default):
82 -+output-format __FILE__(__LINE__): __ERROR__
83 -# Alternative syntax:
84 -#+output-format __FILE__:__LINE__: __ERROR__
85 -
86 -
87 -### Context
88 -# Show the in-line position of the error.
89 -# Use "+context" to display or "-context" to suppress.
90 -#
91 -+context
92 -
93 -
94 -### Control Comments
95 -# Both JavaScript Lint and the JScript interpreter confuse each other with the syntax for
96 -# the /*@keyword@*/ control comments and JScript conditional comments. (The latter is
97 -# enabled in JScript with @cc_on@). The /*jsl:keyword*/ syntax is preferred for this reason,
98 -# although legacy control comments are enabled by default for backward compatibility.
99 -#
100 --legacy_control_comments
101 -
102 -
103 -### Defining identifiers
104 -# By default, "option explicit" is enabled on a per-file basis.
105 -# To enable this for all files, use "+always_use_option_explicit"
106 --always_use_option_explicit
107 -
108 -# Define certain identifiers of which the lint is not aware.
109 -# (Use this in conjunction with the "undeclared identifier" warning.)
110 -#
111 -# Common uses for webpages might be:
112 -+define __dirname
113 -+define clearInterval
114 -+define clearTimeout
115 -+define console
116 -+define exports
117 -+define global
118 -+define process
119 -+define require
120 -+define setInterval
121 -+define setTimeout
122 -+define Buffer
123 -+define JSON
124 -+define Math
125 -
126 -### JavaScript Version
127 -# To change the default JavaScript version:
128 -#+default-type text/javascript;version=1.5
129 -#+default-type text/javascript;e4x=1
130 -
131 -### Files
132 -# Specify which files to lint
133 -# Use "+recurse" to enable recursion (disabled by default).
134 -# To add a set of files, use "+process FileName", "+process Folder\Path\*.js",
135 -# or "+process Folder\Path\*.htm".
136 -#
137 -
1 -/*
2 - * extsprintf.js: extended POSIX-style sprintf
3 - */
4 -
5 -var mod_assert = require('assert');
6 -var mod_util = require('util');
7 -
8 -/*
9 - * Public interface
10 - */
11 -exports.sprintf = jsSprintf;
12 -exports.printf = jsPrintf;
13 -exports.fprintf = jsFprintf;
14 -
15 -/*
16 - * Stripped down version of s[n]printf(3c). We make a best effort to throw an
17 - * exception when given a format string we don't understand, rather than
18 - * ignoring it, so that we won't break existing programs if/when we go implement
19 - * the rest of this.
20 - *
21 - * This implementation currently supports specifying
22 - * - field alignment ('-' flag),
23 - * - zero-pad ('0' flag)
24 - * - always show numeric sign ('+' flag),
25 - * - field width
26 - * - conversions for strings, decimal integers, and floats (numbers).
27 - * - argument size specifiers. These are all accepted but ignored, since
28 - * Javascript has no notion of the physical size of an argument.
29 - *
30 - * Everything else is currently unsupported, most notably precision, unsigned
31 - * numbers, non-decimal numbers, and characters.
32 - */
33 -function jsSprintf(fmt)
34 -{
35 - var regex = [
36 - '([^%]*)', /* normal text */
37 - '%', /* start of format */
38 - '([\'\\-+ #0]*?)', /* flags (optional) */
39 - '([1-9]\\d*)?', /* width (optional) */
40 - '(\\.([1-9]\\d*))?', /* precision (optional) */
41 - '[lhjztL]*?', /* length mods (ignored) */
42 - '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */
43 - ].join('');
44 -
45 - var re = new RegExp(regex);
46 - var args = Array.prototype.slice.call(arguments, 1);
47 - var flags, width, precision, conversion;
48 - var left, pad, sign, arg, match;
49 - var ret = '';
50 - var argn = 1;
51 -
52 - mod_assert.equal('string', typeof (fmt));
53 -
54 - while ((match = re.exec(fmt)) !== null) {
55 - ret += match[1];
56 - fmt = fmt.substring(match[0].length);
57 -
58 - flags = match[2] || '';
59 - width = match[3] || 0;
60 - precision = match[4] || '';
61 - conversion = match[6];
62 - left = false;
63 - sign = false;
64 - pad = ' ';
65 -
66 - if (conversion == '%') {
67 - ret += '%';
68 - continue;
69 - }
70 -
71 - if (args.length === 0)
72 - throw (new Error('too few args to sprintf'));
73 -
74 - arg = args.shift();
75 - argn++;
76 -
77 - if (flags.match(/[\' #]/))
78 - throw (new Error(
79 - 'unsupported flags: ' + flags));
80 -
81 - if (precision.length > 0)
82 - throw (new Error(
83 - 'non-zero precision not supported'));
84 -
85 - if (flags.match(/-/))
86 - left = true;
87 -
88 - if (flags.match(/0/))
89 - pad = '0';
90 -
91 - if (flags.match(/\+/))
92 - sign = true;
93 -
94 - switch (conversion) {
95 - case 's':
96 - if (arg === undefined || arg === null)
97 - throw (new Error('argument ' + argn +
98 - ': attempted to print undefined or null ' +
99 - 'as a string'));
100 - ret += doPad(pad, width, left, arg.toString());
101 - break;
102 -
103 - case 'd':
104 - arg = Math.floor(arg);
105 - /*jsl:fallthru*/
106 - case 'f':
107 - sign = sign && arg > 0 ? '+' : '';
108 - ret += sign + doPad(pad, width, left,
109 - arg.toString());
110 - break;
111 -
112 - case 'x':
113 - ret += doPad(pad, width, left, arg.toString(16));
114 - break;
115 -
116 - case 'j': /* non-standard */
117 - if (width === 0)
118 - width = 10;
119 - ret += mod_util.inspect(arg, false, width);
120 - break;
121 -
122 - case 'r': /* non-standard */
123 - ret += dumpException(arg);
124 - break;
125 -
126 - default:
127 - throw (new Error('unsupported conversion: ' +
128 - conversion));
129 - }
130 - }
131 -
132 - ret += fmt;
133 - return (ret);
134 -}
135 -
136 -function jsPrintf() {
137 - var args = Array.prototype.slice.call(arguments);
138 - args.unshift(process.stdout);
139 - jsFprintf.apply(null, args);
140 -}
141 -
142 -function jsFprintf(stream) {
143 - var args = Array.prototype.slice.call(arguments, 1);
144 - return (stream.write(jsSprintf.apply(this, args)));
145 -}
146 -
147 -function doPad(chr, width, left, str)
148 -{
149 - var ret = str;
150 -
151 - while (ret.length < width) {
152 - if (left)
153 - ret += chr;
154 - else
155 - ret = chr + ret;
156 - }
157 -
158 - return (ret);
159 -}
160 -
161 -/*
162 - * This function dumps long stack traces for exceptions having a cause() method.
163 - * See node-verror for an example.
164 - */
165 -function dumpException(ex)
166 -{
167 - var ret;
168 -
169 - if (!(ex instanceof Error))
170 - throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));
171 -
172 - /* Note that V8 prepends "ex.stack" with ex.toString(). */
173 - ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;
174 -
175 - if (ex.cause && typeof (ex.cause) === 'function') {
176 - var cex = ex.cause();
177 - if (cex) {
178 - ret += '\nCaused by: ' + dumpException(cex);
179 - }
180 - }
181 -
182 - return (ret);
183 -}
1 -{
2 - "name": "extsprintf",
3 - "version": "1.3.0",
4 - "description": "extended POSIX-style sprintf",
5 - "main": "./lib/extsprintf.js",
6 - "repository": {
7 - "type": "git",
8 - "url": "git://github.com/davepacheco/node-extsprintf.git"
9 - },
10 - "engines": [
11 - "node >=0.6.0"
12 - ],
13 - "license": "MIT"
14 -}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.