-
Notifications
You must be signed in to change notification settings - Fork 112
/
cmd.js
executable file
·373 lines (321 loc) · 9.69 KB
/
cmd.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var semver = require('semver')
var proc = require('child_process')
var pick = require('object.pick')
var extend = require('xtend/mutable')
var deepEqual = require('deep-equal')
var find = require('findit')
var minimist = require('minimist')
var parallel = require('run-parallel')
var yarnlock = require('@yarnpkg/lockfile')
var allShims = require('./shims')
var coreList = require('./coreList')
var browser = require('./browser')
var pkgPath = path.join(process.cwd(), 'package.json')
var pkg = require(pkgPath)
var hackFiles = require('./pkg-hacks')
var argv = minimist(process.argv.slice(2), {
alias: {
h: 'help',
i: 'install',
e: 'hack',
o: 'overwrite',
y: 'yarn'
}
})
var BASE_INSTALL_LINE = argv.yarn ? 'yarn add' : 'npm install --save'
if (argv.help) {
runHelp()
process.exit(0)
} else {
run()
}
function run () {
var toShim
if (argv.install) {
if (argv.install === true) {
toShim = coreList
} else {
toShim = argv.install.split(',')
.map(function (name) {
return name.trim()
})
}
} else {
toShim = coreList
}
if (toShim.indexOf('stream') !== -1) {
toShim.push(
'_stream_transform',
'_stream_readable',
'_stream_writable',
'_stream_duplex',
'_stream_passthrough',
'readable-stream'
)
}
if (toShim.indexOf('crypto') !== -1) {
toShim.push('react-native-randombytes')
}
if (argv.install) {
installShims({
modules: toShim,
overwrite: argv.overwrite
}, function (err) {
if (err) throw err
runHacks()
})
} else {
runHacks()
}
function runHacks () {
hackPackageJSONs(toShim, function (err) {
if (err) throw err
if (argv.hack) {
if (argv.hack === true) hackFiles()
else hackFiles([].concat(argv.hack))
}
})
}
}
function installShims ({ modules, overwrite }, done) {
if (!overwrite) {
modules = modules.filter(name => {
const shimPackageName = browser[name] || name
if (pkg.dependencies[shimPackageName]) {
log(`not overwriting "${shimPackageName}"`)
return false
}
return true
})
}
var shimPkgNames = modules
.map(function (m) {
return browser[m] || m
})
.filter(function (shim) {
return !/^_/.test(shim) && (shim[0] === '@' || shim.indexOf('/') === -1)
})
if (!shimPkgNames.length) {
return finish()
}
// Load the exact package versions from the lockfile
var lockfile
if (argv.yarn) {
if (fs.existsSync('yarn.lock')) {
let result = yarnlock.parse(fs.readFileSync('yarn.lock', 'utf8'))
if (result.type == 'success') {
lockfile = result.object
}
}
} else {
var lockpath = path.join(process.cwd(), 'package-lock.json')
if (fs.existsSync(lockpath)) {
let result = require(lockpath)
if (result && result.dependencies) {
lockfile = result.dependencies
}
}
}
parallel(shimPkgNames.map(function (name) {
var modPath = path.resolve('./node_modules/' + name)
return function (cb) {
fs.exists(modPath, function (exists) {
if (!exists) return cb()
var install = true
if (lockfile) {
// Use the lockfile to resolve installed version of package
if (argv.yarn) {
if (`${name}@${allShims[name]}` in lockfile) {
install = false
}
} else {
var lockfileVer = (lockfile[name] || {}).version
var targetVer = allShims[name]
if (semver.valid(lockfileVer)) {
if (semver.satisfies(lockfileVer, targetVer)) {
install = false
}
} else if (lockfileVer) {
// To be considered up-to-date, we need an exact match,
// after doing some normalization of github url's
if (lockfileVer.startsWith('github:')) {
lockfileVer = lockfileVer.slice(7)
}
if (lockfileVer.indexOf(targetVer) == 0) {
install = false
}
}
}
} else {
// Fallback to using the version from the dependency's package.json
var pkgJson = require(modPath + '/package.json')
if (/^git\:\/\//.test(pkgJson._resolved)) {
var hash = allShims[name].split('#')[1]
if (hash && pkgJson.gitHead.indexOf(hash) === 0) {
install = false
}
} else {
var existingVerNpm5 = (/\-([^\-]+)\.tgz/.exec(pkgJson.version) || [null, null])[1]
var existingVer = existingVerNpm5 || pkgJson.version
if (semver.satisfies(existingVer, allShims[name])) {
install = false
}
}
}
if (!install) {
log('not reinstalling ' + name)
shimPkgNames.splice(shimPkgNames.indexOf(name), 1)
}
cb()
})
}
}), function (err) {
if (err) throw err
if (!shimPkgNames.length) {
return finish()
}
var installLine = BASE_INSTALL_LINE + ' '
shimPkgNames.forEach(function (name) {
let version = allShims[name]
if (!version) return
if (version.indexOf('/') === -1) {
if (argv.yarn) {
log('installing from yarn', name)
} else {
log('installing from npm', name)
}
installLine += name + '@' + version
} else {
// github url
log('installing from github', name)
installLine += version.match(/([^\/]+\/[^\/]+)$/)[1]
}
pkg.dependencies[name] = version
installLine += ' '
})
fs.writeFile(pkgPath, prettify(pkg), function (err) {
if (err) throw err
if (installLine.trim() === BASE_INSTALL_LINE) {
return finish()
}
log('installing:', installLine)
proc.execSync(installLine, {
cwd: process.cwd(),
env: process.env,
stdio: 'inherit'
})
finish()
})
})
function finish () {
copyShim(done)
}
}
function copyShim (cb) {
fs.exists('./shim.js', function (exists) {
if (exists) {
log('not overwriting shim.js. For the latest version, see rn-nodeify/shim.js')
return cb()
}
fs.readFile(path.join(__dirname, 'shim.js'), { encoding: 'utf8' }, function (err, contents) {
if (err) return cb(err)
fs.writeFile('./shim.js', contents, cb)
})
})
}
function hackPackageJSONs (modules, done) {
fixPackageJSON(modules, './package.json', true)
var finder = find('./node_modules')
finder.on('file', function (file) {
if (path.basename(file) !== 'package.json') return
fixPackageJSON(modules, file, true)
})
finder.once('end', done)
}
function fixPackageJSON (modules, file, overwrite) {
if (file.split(path.sep).indexOf('react-native') >= 0) return
var contents = fs.readFileSync(path.resolve(file), { encoding: 'utf8' })
// var browser = pick(baseBrowser, modules)
var pkgJson
try {
pkgJson = JSON.parse(contents)
} catch (err) {
console.warn('failed to parse', file)
return
}
// if (shims[pkgJson.name]) {
// log('skipping', pkgJson.name)
// return
// }
// if (pkgJson.name === 'readable-stream') debugger
var orgBrowser = pkgJson['react-native'] || pkgJson.browser || pkgJson.browserify || {}
if (typeof orgBrowser === 'string') {
orgBrowser = {}
orgBrowser[pkgJson.main || 'index.js'] = pkgJson['react-native'] || pkgJson.browser || pkgJson.browserify
}
var depBrowser = extend({}, orgBrowser)
for (var p in browser) {
if (modules.indexOf(p) === -1) continue
if (!(p in orgBrowser)) {
depBrowser[p] = browser[p]
} else {
if (!overwrite && orgBrowser[p] !== browser[p]) {
log('not overwriting mapping', p, orgBrowser[p])
} else {
depBrowser[p] = browser[p]
}
}
}
modules.forEach(function (p) {
if (depBrowser[p] === false && browser[p] !== false) {
log('removing browser exclude', file, p)
delete depBrowser[p]
}
})
const { main } = pkgJson
if (typeof main === 'string') {
const alt = main.startsWith('./') ? main.slice(2) : './' + main
if (depBrowser[alt]) {
depBrowser[main] = depBrowser[alt]
log(`normalized "main" browser mapping in ${pkgJson.name}, fixed here: https://github.com/facebook/metro-bundler/pull/3`)
delete depBrowser[alt]
}
}
if (pkgJson.name === 'constants-browserify') {
// otherwise react-native packager chokes for some reason
delete depBrowser.constants
}
if (!deepEqual(orgBrowser, depBrowser)) {
pkgJson.browser = pkgJson['react-native'] = depBrowser
delete pkgJson.browserify
fs.writeFileSync(file, prettify(pkgJson))
}
}
function runHelp () {
log(function () {
/*
Usage:
rn-nodeify --install dns,stream,http,https
rn-nodeify --install # installs all core shims
rn-nodeify --hack # run all package-specific hacks
rn-nodeify --hack rusha,fssync # run some package-specific hacks
Options:
-h --help show usage
-e, --hack run package-specific hacks (list or leave blank to run all)
-i, --install install shims (list or leave blank to install all)
-o, --overwrite updates installed packages if a newer version is available
-y, --yarn use yarn to install packages instead of npm (experimental)
Please report bugs! https://github.com/mvayngrib/rn-nodeify/issues
*/
}.toString().split(/\n/).slice(2, -2).join('\n'))
process.exit(0)
}
function log () {
console.log.apply(console, arguments)
}
function prettify (json) {
return JSON.stringify(json, null, 2) + '\n'
}