-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
111 lines (99 loc) · 2.54 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/**
* Copyright(c) repo-utils and other contributors.
* MIT Licensed
*
* Authors:
* dead_horse <[email protected]> (http://deadhorse.me)
*/
'use strict';
/**
* Module dependencies.
*/
var urllib = require('urllib');
var fs = require('fs');
var path = require('path');
function parseConfig(configFile) {
var cookie = '';
var userconfig = {};
try {
var cookieStart = false;
var tmpCookie = [];
var cfgs = fs.readFileSync(configFile, 'utf8').split('\n');
for (var i = 0; i < cfgs.length; i++) {
var cfg = cfgs[i];
if (cfg === '[_token]') {
cookieStart = true;
continue;
}
if (!cookieStart) {
cfg = cfg.match(/(.*?)\s+=\s+(.*)/);
if (!cfg) {
continue;
}
userconfig[cfg[1]] = cfg[2];
} else {
tmpCookie.push(cfg);
}
}
cookie = tmpCookie.join(';');
} catch (err) {
//ignore
}
return {
cookie: cookie,
userconfig: userconfig
};
}
var root;
if (process.platform === 'win32') {
root = process.env.USERPROFILE || process.env.APPDATA || process.env.TMP || process.env.TEMP;
} else {
root = process.env.HOME || process.env.TMPDIR || '/tmp';
}
var DEFAULT_NPM_OPTIONS = {
registry: 'https://registry.npmjs.org',
configFile: path.join(root, '.npmrc')
};
module.exports = function (request, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
for (var key in DEFAULT_NPM_OPTIONS) {
options[key] = options[key] || DEFAULT_NPM_OPTIONS[key];
}
var reqOptions = {
method: request.method,
headers: {},
data: request.data,
timeout: request.timeout || 30000,
gzip: true,
};
var npmConfigInfo = parseConfig(options.configFile);
if (npmConfigInfo.cookie) {
reqOptions.headers.Cookie = npmConfigInfo.cookie;
}
if (npmConfigInfo.userconfig._auth) {
reqOptions.headers.authorization = 'Basic ' + npmConfigInfo.userconfig._auth;
}
if (reqOptions.data) {
reqOptions.headers['Content-Length'] = JSON.stringify(reqOptions.data).length;
reqOptions.headers['Content-Type'] = 'application/json';
}
var host = options.registry.replace(/\/$/, '');
request.path.replace(/^\//, '');
var url = host + '/' + request.path;
urllib.request(url, reqOptions, function (err, data, res) {
var parsed = {};
if (err) {
return callback(err, parsed, data, res);
}
try {
parsed = JSON.parse(data.toString());
} catch (err) {
//ignore
}
callback(err, parsed, data, res);
});
};