generate-ip 2.8.0 โ 2.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -8
- package/bin/generate-ip +3 -3
- package/bin/generate-ipv4 +3 -3
- package/bin/generate-ipv6 +3 -3
- package/bin/generate-mac +3 -3
- package/bin/generateip +3 -3
- package/bin/generateipv4 +3 -3
- package/bin/generateipv6 +3 -3
- package/bin/generatemac +3 -3
- package/dist/cli/.cache/locales.json +102 -0
- package/dist/cli/index.js +35 -0
- package/dist/cli/lib/data.js +30 -0
- package/dist/cli/lib/init.js +44 -0
- package/dist/cli/lib/jsdelivr.js +10 -0
- package/dist/cli/lib/language.js +93 -0
- package/dist/cli/lib/log.js +106 -0
- package/dist/cli/lib/pkg.js +20 -0
- package/dist/cli/lib/settings.js +119 -0
- package/docs/README.md +8 -8
- package/package.json +2 -1
- package/dist/cli/index.min.js +0 -8
- package/dist/cli/lib/data.min.js +0 -6
- package/dist/cli/lib/init.min.js +0 -6
- package/dist/cli/lib/jsdelivr.min.js +0 -6
- package/dist/cli/lib/language.min.js +0 -7
- package/dist/cli/lib/log.min.js +0 -22
- package/dist/cli/lib/pkg.min.js +0 -6
- package/dist/cli/lib/settings.min.js +0 -7
package/README.md
CHANGED
|
@@ -10,12 +10,12 @@
|
|
|
10
10
|
|
|
11
11
|
<a href="#%EF%B8%8F-mit-license">
|
|
12
12
|
<img height=31 src="https://img.shields.io/badge/License-MIT-orange.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge"></a>
|
|
13
|
-
<a href="https://github.com/adamlui/js-utils/releases/tag/generate-ip-2.8.
|
|
14
|
-
<img height=31 src="https://img.shields.io/badge/Latest_Build-2.8.
|
|
13
|
+
<a href="https://github.com/adamlui/js-utils/releases/tag/generate-ip-2.8.2">
|
|
14
|
+
<img height=31 src="https://img.shields.io/badge/Latest_Build-2.8.2-44cc11.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
|
|
15
15
|
<a href="https://www.npmjs.com/package/generate-ip?activeTab=code">
|
|
16
16
|
<img height=31 src="https://img.shields.io/npm/unpacked-size/generate-ip?style=for-the-badge&logo=ebox&logoColor=white&labelColor=464646&color=blue"></a>
|
|
17
|
-
<a href="https://github.com/adamlui/js-utils/blob/generate-ip-2.8.
|
|
18
|
-
<img height=31 src="https://img.shields.io/github/size/adamlui/js-utils/generate-ip/dist/generate-ip.min.js?branch=generate-ip-2.8.
|
|
17
|
+
<a href="https://github.com/adamlui/js-utils/blob/generate-ip-2.8.2/generate-ip/dist/generate-ip.min.js">
|
|
18
|
+
<img height=31 src="https://img.shields.io/github/size/adamlui/js-utils/generate-ip/dist/generate-ip.min.js?branch=generate-ip-2.8.2&label=Minified%20Size&logo=databricks&logoColor=white&labelColor=464646&color=ff69b4&style=for-the-badge"></a>
|
|
19
19
|
<a href="https://sonarcloud.io/component_measures?metric=new_vulnerabilities&id=adamlui_js-utils:generate-ip/src/generate-ip.js">
|
|
20
20
|
<img height=31 src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsonarcloud.io%2Fapi%2Fmeasures%2Fcomponent%3Fcomponent%3Dadamlui_js-utils%3Agenerate-ip%2Fsrc%2Fgenerate-ip.js%26metricKeys%3Dvulnerabilities&query=%24.component.measures.0.value&style=for-the-badge&logo=sonarcloud&logoColor=white&labelColor=464646&label=Vulnerabilities&color=gold"></a>
|
|
21
21
|
<a href="https://github.com/toolleeo/cli-apps#networking">
|
|
@@ -87,14 +87,14 @@ const { ipv4, ipv6, mac } = require('generate-ip')
|
|
|
87
87
|
#### <> HTML script tag:
|
|
88
88
|
|
|
89
89
|
```html
|
|
90
|
-
<script src="https://cdn.jsdelivr.net/npm/generate-ip@2.8.
|
|
90
|
+
<script src="https://cdn.jsdelivr.net/npm/generate-ip@2.8.2/dist/generate-ip.min.js"></script>
|
|
91
91
|
```
|
|
92
92
|
|
|
93
93
|
#### ES6:
|
|
94
94
|
|
|
95
95
|
```js
|
|
96
96
|
(async () => {
|
|
97
|
-
await import('https://cdn.jsdelivr.net/npm/generate-ip@2.8.
|
|
97
|
+
await import('https://cdn.jsdelivr.net/npm/generate-ip@2.8.2/dist/generate-ip.min.js')
|
|
98
98
|
// Your code here...
|
|
99
99
|
})()
|
|
100
100
|
```
|
|
@@ -103,7 +103,7 @@ const { ipv4, ipv6, mac } = require('generate-ip')
|
|
|
103
103
|
|
|
104
104
|
```js
|
|
105
105
|
...
|
|
106
|
-
// @require https://cdn.jsdelivr.net/npm/generate-ip@2.8.
|
|
106
|
+
// @require https://cdn.jsdelivr.net/npm/generate-ip@2.8.2/dist/generate-ip.min.js
|
|
107
107
|
// ==/UserScript==
|
|
108
108
|
|
|
109
109
|
// Your code here...
|
|
@@ -111,7 +111,7 @@ const { ipv4, ipv6, mac } = require('generate-ip')
|
|
|
111
111
|
|
|
112
112
|
<br>
|
|
113
113
|
|
|
114
|
-
๐ **Note:** To always import the latest version (not recommended in production!) remove the `@2.8.
|
|
114
|
+
๐ **Note:** To always import the latest version (not recommended in production!) remove the `@2.8.2` version tag from the jsDelivr URL: `https://cdn.jsdelivr.net/npm/generate-ip/dist/generate-ip.min.js`
|
|
115
115
|
|
|
116
116
|
<br>
|
|
117
117
|
|
package/bin/generate-ip
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
require('child_process').spawnSync(
|
|
4
|
-
[require.
|
|
3
|
+
require('child_process').spawnSync(
|
|
4
|
+
'node', [require('path').join(__dirname, '../dist/cli'), ...process.argv.slice(2)],
|
|
5
5
|
{ stdio: 'inherit' }
|
|
6
|
-
)
|
|
6
|
+
)
|
package/bin/generate-ipv4
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
require('child_process').spawnSync(
|
|
4
|
-
[require.
|
|
3
|
+
require('child_process').spawnSync(
|
|
4
|
+
'node', [require('path').join(__dirname, '../dist/cli'), ...process.argv.slice(2)],
|
|
5
5
|
{ stdio: 'inherit' }
|
|
6
|
-
)
|
|
6
|
+
)
|
package/bin/generate-ipv6
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
require('child_process').spawnSync(
|
|
4
|
-
[require.
|
|
3
|
+
require('child_process').spawnSync(
|
|
4
|
+
'node', [require('path').join(__dirname, '../dist/cli'), '--ipv6', ...process.argv.slice(2)],
|
|
5
5
|
{ stdio: 'inherit' }
|
|
6
|
-
)
|
|
6
|
+
)
|
package/bin/generate-mac
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
require('child_process').spawnSync(
|
|
4
|
-
[require.
|
|
3
|
+
require('child_process').spawnSync(
|
|
4
|
+
'node', [require('path').join(__dirname, '../dist/cli'), '--mac', ...process.argv.slice(2)],
|
|
5
5
|
{ stdio: 'inherit' }
|
|
6
|
-
)
|
|
6
|
+
)
|
package/bin/generateip
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
require('child_process').spawnSync(
|
|
4
|
-
[require.
|
|
3
|
+
require('child_process').spawnSync(
|
|
4
|
+
'node', [require('path').join(__dirname, '../dist/cli'), ...process.argv.slice(2)],
|
|
5
5
|
{ stdio: 'inherit' }
|
|
6
|
-
)
|
|
6
|
+
)
|
package/bin/generateipv4
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
require('child_process').spawnSync(
|
|
4
|
-
[require.
|
|
3
|
+
require('child_process').spawnSync(
|
|
4
|
+
'node', [require('path').join(__dirname, '../dist/cli'), ...process.argv.slice(2)],
|
|
5
5
|
{ stdio: 'inherit' }
|
|
6
|
-
)
|
|
6
|
+
)
|
package/bin/generateipv6
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
require('child_process').spawnSync(
|
|
4
|
-
[require.
|
|
3
|
+
require('child_process').spawnSync(
|
|
4
|
+
'node', [require('path').join(__dirname, '../dist/cli'), '--ipv6', ...process.argv.slice(2)],
|
|
5
5
|
{ stdio: 'inherit' }
|
|
6
|
-
)
|
|
6
|
+
)
|
package/bin/generatemac
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
require('child_process').spawnSync(
|
|
4
|
-
[require.
|
|
3
|
+
require('child_process').spawnSync(
|
|
4
|
+
'node', [require('path').join(__dirname, '../dist/cli'), '--mac', ...process.argv.slice(2)],
|
|
5
5
|
{ stdio: 'inherit' }
|
|
6
|
-
)
|
|
6
|
+
)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
[
|
|
2
|
+
"af",
|
|
3
|
+
"am",
|
|
4
|
+
"ar",
|
|
5
|
+
"az",
|
|
6
|
+
"be",
|
|
7
|
+
"bg",
|
|
8
|
+
"bn",
|
|
9
|
+
"bo",
|
|
10
|
+
"bs",
|
|
11
|
+
"ca",
|
|
12
|
+
"cs",
|
|
13
|
+
"cy",
|
|
14
|
+
"da",
|
|
15
|
+
"de",
|
|
16
|
+
"dv",
|
|
17
|
+
"dz",
|
|
18
|
+
"el",
|
|
19
|
+
"en",
|
|
20
|
+
"eo",
|
|
21
|
+
"es",
|
|
22
|
+
"et",
|
|
23
|
+
"eu",
|
|
24
|
+
"fa",
|
|
25
|
+
"fi",
|
|
26
|
+
"fo",
|
|
27
|
+
"fr",
|
|
28
|
+
"gd",
|
|
29
|
+
"gl",
|
|
30
|
+
"gu",
|
|
31
|
+
"he",
|
|
32
|
+
"hi",
|
|
33
|
+
"hr",
|
|
34
|
+
"ht",
|
|
35
|
+
"hu",
|
|
36
|
+
"hy",
|
|
37
|
+
"id",
|
|
38
|
+
"is",
|
|
39
|
+
"it",
|
|
40
|
+
"ja",
|
|
41
|
+
"ka",
|
|
42
|
+
"kk",
|
|
43
|
+
"km",
|
|
44
|
+
"kn",
|
|
45
|
+
"ko",
|
|
46
|
+
"ku",
|
|
47
|
+
"ky",
|
|
48
|
+
"la",
|
|
49
|
+
"lb",
|
|
50
|
+
"lo",
|
|
51
|
+
"lt",
|
|
52
|
+
"lv",
|
|
53
|
+
"mg",
|
|
54
|
+
"mi",
|
|
55
|
+
"mk",
|
|
56
|
+
"ml",
|
|
57
|
+
"mn",
|
|
58
|
+
"ms",
|
|
59
|
+
"mt",
|
|
60
|
+
"my",
|
|
61
|
+
"ne",
|
|
62
|
+
"nl",
|
|
63
|
+
"no",
|
|
64
|
+
"ny",
|
|
65
|
+
"pa",
|
|
66
|
+
"pl",
|
|
67
|
+
"ps",
|
|
68
|
+
"pt",
|
|
69
|
+
"ro",
|
|
70
|
+
"ru",
|
|
71
|
+
"rw",
|
|
72
|
+
"sg",
|
|
73
|
+
"si",
|
|
74
|
+
"sk",
|
|
75
|
+
"sl",
|
|
76
|
+
"sm",
|
|
77
|
+
"sn",
|
|
78
|
+
"so",
|
|
79
|
+
"sr",
|
|
80
|
+
"sv",
|
|
81
|
+
"sw",
|
|
82
|
+
"ta",
|
|
83
|
+
"te",
|
|
84
|
+
"tg",
|
|
85
|
+
"th",
|
|
86
|
+
"ti",
|
|
87
|
+
"tk",
|
|
88
|
+
"tn",
|
|
89
|
+
"tr",
|
|
90
|
+
"uk",
|
|
91
|
+
"ur",
|
|
92
|
+
"uz",
|
|
93
|
+
"vi",
|
|
94
|
+
"xh",
|
|
95
|
+
"yi",
|
|
96
|
+
"zh",
|
|
97
|
+
"zh_CN",
|
|
98
|
+
"zh_HK",
|
|
99
|
+
"zh_SG",
|
|
100
|
+
"zh_TW",
|
|
101
|
+
"zu"
|
|
102
|
+
]
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
(async () => {
|
|
4
|
+
'use strict'
|
|
5
|
+
|
|
6
|
+
globalThis.env = {
|
|
7
|
+
args: process.argv.slice(2),
|
|
8
|
+
devMode: /[\\/]src(?:[\\/]|$)/i.test(__dirname)
|
|
9
|
+
}
|
|
10
|
+
env.debugMode = env.args.some(arg => /^--?debug(?:-?mode)?$/.test(arg))
|
|
11
|
+
|
|
12
|
+
// Import LIBS
|
|
13
|
+
const clipboardy = require('node-clipboardy'),
|
|
14
|
+
generateIP = require(`../generate-ip${ env.devMode ? '' : '.min' }.js`),
|
|
15
|
+
init = require('./lib/init'),
|
|
16
|
+
log = require('./lib/log')
|
|
17
|
+
|
|
18
|
+
await init.cli()
|
|
19
|
+
|
|
20
|
+
// Exec CMD arg if passed
|
|
21
|
+
if (cli.config.init) return init.configFile()
|
|
22
|
+
else if (cli.config.help) return log.help()
|
|
23
|
+
else if (cli.config.version) return log.version()
|
|
24
|
+
|
|
25
|
+
// Log/copy random IP(s)
|
|
26
|
+
const genOptions = {
|
|
27
|
+
qty: cli.config.qty,
|
|
28
|
+
sequential: cli.config.sequential,
|
|
29
|
+
network: cli.config.network,
|
|
30
|
+
verbose: !cli.config.quietMode
|
|
31
|
+
}
|
|
32
|
+
clipboardy.writeSync([].concat(generateIP[cli.config.mode || 'ipv4'].generate(genOptions)).join('\n'))
|
|
33
|
+
log.ifNotQuiet(`\n${cli.msgs.info_copyingToClip}...`)
|
|
34
|
+
|
|
35
|
+
})()
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
|
|
3
|
+
atomicWrite(filePath, data, encoding = 'utf8') { // to prevent TOCTOU
|
|
4
|
+
const fs = require('fs'),
|
|
5
|
+
path = require('path'),
|
|
6
|
+
tmpPath = path.join(path.dirname(filePath), `.${path.basename(filePath)}.tmp`)
|
|
7
|
+
fs.writeFileSync(tmpPath, data, encoding) ; fs.renameSync(tmpPath, filePath)
|
|
8
|
+
},
|
|
9
|
+
|
|
10
|
+
fetch(url) { // to support Node.js < v21
|
|
11
|
+
return typeof fetch == 'undefined' ? new Promise((resolve, reject) => { // using https?.get()
|
|
12
|
+
const protocol = url.match(/^([^:]+):\/\//)[1]
|
|
13
|
+
if (!/^https?$/.test(protocol))
|
|
14
|
+
reject(new Error(`${cli.msgs.error_invalidURL}.`))
|
|
15
|
+
require(protocol).get(url, resp => {
|
|
16
|
+
let rawData = ''
|
|
17
|
+
resp.on('data', chunk => rawData += chunk)
|
|
18
|
+
resp.on('end', () => resolve({ json: () => JSON.parse(rawData) }))
|
|
19
|
+
}).on('error', reject)
|
|
20
|
+
}) : fetch(url) // using Node.js fetch()
|
|
21
|
+
},
|
|
22
|
+
|
|
23
|
+
flatten(json, { key = 'message' } = {}) { // eliminate need to ref nested keys
|
|
24
|
+
const flatObj = {}
|
|
25
|
+
for (const jsonKey in json) flatObj[jsonKey] =
|
|
26
|
+
typeof json[jsonKey] == 'object' && key in json[jsonKey] ? json[jsonKey][key]
|
|
27
|
+
: json[jsonKey]
|
|
28
|
+
return flatObj
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const language = require('./language'),
|
|
2
|
+
log = require('./log'),
|
|
3
|
+
settings = require('./settings')
|
|
4
|
+
|
|
5
|
+
const dataPath = `../../${ env.devMode ? '../' : 'data/' }`
|
|
6
|
+
|
|
7
|
+
module.exports = {
|
|
8
|
+
|
|
9
|
+
async cli() {
|
|
10
|
+
Object.assign(globalThis.cli ??= {}, require(`${dataPath}package-data.json`))
|
|
11
|
+
cli.lang = settings.load('uiLang') || (
|
|
12
|
+
env.debugMode ? language.generateRandomLang({ excludes: ['en'] }) : language.getSysLang() )
|
|
13
|
+
cli.msgs = await language.getMsgs(cli.lang)
|
|
14
|
+
cli.urls.cliDocs ||= `${cli.urls.docs}/#-command-line-usage`
|
|
15
|
+
settings.load() // all keys to cli.config
|
|
16
|
+
},
|
|
17
|
+
|
|
18
|
+
async configFile(filename = settings.configFilename) {
|
|
19
|
+
const fs = require('fs'),
|
|
20
|
+
path = require('path'),
|
|
21
|
+
paths = { target: path.resolve(process.cwd(), filename) }
|
|
22
|
+
|
|
23
|
+
if (fs.existsSync(paths.target)) // use existing config file
|
|
24
|
+
return log.warn(`${cli.msgs.warn_configFileExists}:`, paths.target)
|
|
25
|
+
if (fs.existsSync(paths.src = path.resolve(__dirname, `${dataPath}${filename}`)))
|
|
26
|
+
fs.copyFileSync(paths.src, paths.target) // use found template
|
|
27
|
+
|
|
28
|
+
else { // use jsDelivr copy
|
|
29
|
+
const jsdURL = `${require('./jsdelivr').pkgVerURL}/${filename}/`
|
|
30
|
+
log.data(`${cli.msgs.info_fetchingRemoteConfigFrom} ${jsdURL}...`)
|
|
31
|
+
try {
|
|
32
|
+
const data = require('./data'),
|
|
33
|
+
resp = await data.fetch(jsdURL)
|
|
34
|
+
if (resp.ok) data.atomicWrite(paths.target, await resp.text())
|
|
35
|
+
else return log.warn(`${cli.msgs.warn_remoteConfigNotFound}: ${jsdURL} (${resp.status})`)
|
|
36
|
+
} catch (err) {
|
|
37
|
+
return log.warn(`${cli.msgs.warn_remoteConfigFailed}: ${jsdURL} ${err.message}`) }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
log.success(`${cli.msgs.info_configFileCreated}: ${paths.target}\n`)
|
|
41
|
+
log.tip(`${cli.msgs.tip_editToSetDefaults}.`)
|
|
42
|
+
log.tip(`${cli.msgs.tip_cliArgsPrioritized}.`)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
|
|
3
|
+
pkgVerURL(version) {
|
|
4
|
+
version ||= cli.version ||= require('./pkg').getVer('local') || 'none'
|
|
5
|
+
const verTag = !/^\d+\.\d+\.\d+$/.test(version) ? 'latest' : `${cli.name}-${version}`
|
|
6
|
+
return `${cli.urls.jsdelivr}@${verTag}/${cli.name}`
|
|
7
|
+
},
|
|
8
|
+
|
|
9
|
+
commitURL(hash = 'latest') { return `${cli.urls.jsdelivr}@${hash}/${cli.name}` }
|
|
10
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
const data = require('./data'),
|
|
2
|
+
log = require('./log')
|
|
3
|
+
|
|
4
|
+
module.exports = {
|
|
5
|
+
|
|
6
|
+
formatCode(langCode) { // to match locale dir name
|
|
7
|
+
return langCode.replace(
|
|
8
|
+
/([a-z]{2,8})[-_]([a-z]{2})/i, (_, lang, region) =>`${lang.toLowerCase()}_${region.toUpperCase()}`) },
|
|
9
|
+
|
|
10
|
+
generateRandomLang({ includes = [], excludes = [] } = {}) {
|
|
11
|
+
const fs = require('fs'),
|
|
12
|
+
path = require('path')
|
|
13
|
+
|
|
14
|
+
let locales = includes.length ? includes : (() => {
|
|
15
|
+
|
|
16
|
+
// Read cache if found
|
|
17
|
+
const cacheDir = path.join(__dirname, '..', '.cache'),
|
|
18
|
+
localeCache = path.join(cacheDir, 'locales.json')
|
|
19
|
+
if (fs.existsSync(localeCache))
|
|
20
|
+
try { return JSON.parse(fs.readFileSync(localeCache, 'utf8')) } catch (err) {}
|
|
21
|
+
|
|
22
|
+
// Discover pkg _locales
|
|
23
|
+
const localesDir = path.resolve(process.cwd(), '_locales')
|
|
24
|
+
if (!fs.existsSync(localesDir)) return ['en']
|
|
25
|
+
const locales = fs.readdirSync(localesDir, { withFileTypes: true })
|
|
26
|
+
.filter(entry => entry.isDirectory()).map(entry => entry.name)
|
|
27
|
+
.filter(name => /^\w{2}[-_]?\w{0,2}$/.test(name))
|
|
28
|
+
|
|
29
|
+
// Cache result
|
|
30
|
+
fs.mkdirSync(cacheDir, { recursive: true })
|
|
31
|
+
data.atomicWrite(localeCache, JSON.stringify(locales, null, 2))
|
|
32
|
+
|
|
33
|
+
return locales
|
|
34
|
+
})()
|
|
35
|
+
|
|
36
|
+
// Filter out excludes
|
|
37
|
+
const excludeSet = new Set(excludes)
|
|
38
|
+
locales = locales.filter(locale => !excludeSet.has(locale))
|
|
39
|
+
|
|
40
|
+
// Get random language
|
|
41
|
+
let randomLang = 'en'
|
|
42
|
+
if (locales.length)
|
|
43
|
+
randomLang = locales[Math.floor(Math.random() * locales.length)]
|
|
44
|
+
log.debug(`Random language: ${randomLang}\n`)
|
|
45
|
+
|
|
46
|
+
return randomLang
|
|
47
|
+
},
|
|
48
|
+
|
|
49
|
+
async getMsgs(langCode = 'en') {
|
|
50
|
+
langCode = module.exports.formatCode(langCode)
|
|
51
|
+
if (env.msgs && langCode == cli.lang) return env.msgs // don't re-fetch same msgs
|
|
52
|
+
|
|
53
|
+
let msgs = data.flatten( // local ones
|
|
54
|
+
require(`../../${ env.devMode ? '../_locales/en/' : 'data/' }messages.json`))
|
|
55
|
+
|
|
56
|
+
if (!langCode.startsWith('en')) { // fetch non-English msgs from jsDelivr
|
|
57
|
+
const msgHostURL = `${require('./jsdelivr').commitURL(cli.commitHashes.locales)}/_locales/`
|
|
58
|
+
let msgHref = `${msgHostURL}${langCode}/messages.json`, msgFetchesTried = 0
|
|
59
|
+
while (msgFetchesTried < 3)
|
|
60
|
+
try { // fetch remote msgs
|
|
61
|
+
msgs = data.flatten(await (await data.fetch(msgHref)).json())
|
|
62
|
+
break
|
|
63
|
+
} catch (err) { // retry up to 2X (region-stripped + EN)
|
|
64
|
+
msgFetchesTried++ ; if (msgFetchesTried >= 3) break
|
|
65
|
+
log.debug(msgHref = langCode.includes('-') && msgFetchesTried == 1 ?
|
|
66
|
+
msgHref.replace(/([^_]*)_[^/]*(\/.*)/, '$1$2') // strip region before retrying
|
|
67
|
+
: `${msgHostURL}en/messages.json` // else use EN msgs
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return msgs
|
|
73
|
+
},
|
|
74
|
+
|
|
75
|
+
getSysLang() {
|
|
76
|
+
try {
|
|
77
|
+
if (process.platform == 'win32')
|
|
78
|
+
return require('child_process').execSync(
|
|
79
|
+
'(Get-Culture).TwoLetterISOLanguageName', { shell: 'powershell', encoding: 'utf-8' }
|
|
80
|
+
).trim()
|
|
81
|
+
else { // macOS/Linux
|
|
82
|
+
const pe = process.env
|
|
83
|
+
return (pe.LANG || pe.LANGUAGE || pe.LC_ALL || pe.LC_MESSAGES || pe.LC_NAME)
|
|
84
|
+
.split('.')[0] // strip encoding e.g. .UTF-8
|
|
85
|
+
}
|
|
86
|
+
} catch (err) {
|
|
87
|
+
log.error(`${cli.msgs.error_failedToFetchSysLang}:`, err.message)
|
|
88
|
+
return 'en'
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
|
|
92
|
+
validateLangCode(code) { return typeof code != 'string' ? false : /^[a-z]{2,8}(?:[-_][a-z]{2,3})?$/i.test(code) }
|
|
93
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
|
|
3
|
+
colors: {
|
|
4
|
+
nc: '\x1b[0m', // no color
|
|
5
|
+
br: '\x1b[1;91m', // bright red
|
|
6
|
+
by: '\x1b[1;33m', // bright yellow
|
|
7
|
+
bo: '\x1b[38;5;214m', // bright orange
|
|
8
|
+
bg: '\x1b[1;92m', // bright green
|
|
9
|
+
bw: '\x1b[1;97m', // bright white
|
|
10
|
+
gry: '\x1b[90m', // gray
|
|
11
|
+
blk: '\x1b[30m', // black
|
|
12
|
+
tlBG: '\x1b[106m' // teal bg
|
|
13
|
+
},
|
|
14
|
+
|
|
15
|
+
configURL() { this.info(`\n${cli.msgs.info_exampleValidConfigFile}: ${cli.urls.config}`) },
|
|
16
|
+
configURLandExit(...args) { this.error(...args) ; this.configURL() ; process.exit(1) },
|
|
17
|
+
data(msg) { console.log(`\n${this.colors.bw}${msg}${this.colors.nc}`) },
|
|
18
|
+
debug(msg) { if (env.debugMode) console.debug(`\n${this.colors.bo}DEBUG:`, msg, this.colors.nc, '\n') },
|
|
19
|
+
dim(msg) { console.log(`${this.colors.gry}${msg}${this.colors.nc}`) },
|
|
20
|
+
error(...args) { console.error(`\n${this.colors.br}ERROR:`, ...args, this.colors.nc) },
|
|
21
|
+
errorAndExit(...args) { this.error(...args) ; this.helpCmdAndDocURL() ; process.exit(1) },
|
|
22
|
+
ifNotQuiet(msg) { if (!cli.config.quietMode) console.info(msg) },
|
|
23
|
+
info(msg) { console.info(`\n${this.colors.by}${msg}${this.colors.nc}`) },
|
|
24
|
+
tip(msg) { console.info(`${this.colors.by}TIP: ${msg}${this.colors.nc}`) },
|
|
25
|
+
success(msg) { console.log(`\n${this.colors.bg}${msg}${this.colors.nc}`) },
|
|
26
|
+
warn(...args) { console.warn(`\n${this.colors.bo}WARNING:`, ...args, this.colors.nc) },
|
|
27
|
+
|
|
28
|
+
help(includeSections = ['header', 'usage', 'params', 'flags', 'cmds']) {
|
|
29
|
+
cli.prefix = `${this.colors.tlBG}${this.colors.blk}\x1b[30m ${cli.name} ${this.colors.nc} `
|
|
30
|
+
const helpSections = {
|
|
31
|
+
header: [
|
|
32
|
+
`\nโ ${cli.prefix}${cli.msgs.appCopyright}.`,
|
|
33
|
+
`${cli.prefix}${cli.msgs.prefix_source}: ${cli.urls.src}`
|
|
34
|
+
],
|
|
35
|
+
usage: [
|
|
36
|
+
`\n${this.colors.bw}o ${cli.msgs.helpSection_usage}:${this.colors.nc}`,
|
|
37
|
+
` ${this.colors.bw}ยป ${this.colors.bg}${cli.cmdFormat}${this.colors.nc}`
|
|
38
|
+
],
|
|
39
|
+
params: [
|
|
40
|
+
`\n${this.colors.bw}o ${cli.msgs.helpSection_params}:${this.colors.nc}`,
|
|
41
|
+
` --qty=n ${cli.msgs.optionDesc_qty}.`,
|
|
42
|
+
` --ui-lang="code" ${cli.msgs.optionDesc_uiLang}.`,
|
|
43
|
+
` --config="path/to/file" ${cli.msgs.optionDesc_config}.`,
|
|
44
|
+
` --network="address" ${cli.msgs.optionDesc_network}.`
|
|
45
|
+
],
|
|
46
|
+
flags: [
|
|
47
|
+
`\n${this.colors.bw}o ${cli.msgs.helpSection_flags}:${this.colors.nc}`,
|
|
48
|
+
` -6, --ipv6 ${cli.msgs.optionDesc_ipv6}.`,
|
|
49
|
+
` -m, --mac ${cli.msgs.optionDesc_mac}.`,
|
|
50
|
+
` -s, --sequential ${cli.msgs.optionDesc_sequential}.`,
|
|
51
|
+
` -q, --quiet ${cli.msgs.optionDesc_quiet}.`
|
|
52
|
+
],
|
|
53
|
+
cmds: [
|
|
54
|
+
`\n${this.colors.bw}o ${cli.msgs.helpSection_cmds}:${this.colors.nc}`,
|
|
55
|
+
` -i, --init ${cli.msgs.optionDesc_init}.`,
|
|
56
|
+
` -h, --help ${cli.msgs.optionDesc_help}.`,
|
|
57
|
+
` -v, --version ${cli.msgs.optionDesc_version}.`
|
|
58
|
+
]
|
|
59
|
+
}
|
|
60
|
+
includeSections.forEach(section => // print valid arg elems
|
|
61
|
+
helpSections[section]?.forEach(line => printHelpMsg(line, /header|usage/.test(section) ? 1 : 29)))
|
|
62
|
+
console.info(`\n${cli.msgs.info_moreHelp}, ${
|
|
63
|
+
cli.msgs.info_visit}: ${this.colors.bw}${cli.urls.cliDocs}${this.colors.nc}`)
|
|
64
|
+
|
|
65
|
+
function printHelpMsg(msg, indent) { // wrap msg + indent 2nd+ lines
|
|
66
|
+
const terminalWidth = process.stdout.columns || 80,
|
|
67
|
+
words = msg.match(/\S+|\s+/g),
|
|
68
|
+
lines = [], prefix = '| '
|
|
69
|
+
|
|
70
|
+
// Split msg into lines of appropriate lengths
|
|
71
|
+
let currentLine = ''
|
|
72
|
+
words.forEach(word => {
|
|
73
|
+
const lineLength = terminalWidth -( !lines.length ? 0 : indent )
|
|
74
|
+
if (currentLine.length + prefix.length + word.length > lineLength) { // cap/store it
|
|
75
|
+
lines.push(!lines.length ? currentLine : currentLine.trimStart())
|
|
76
|
+
currentLine = ''
|
|
77
|
+
}
|
|
78
|
+
currentLine += word
|
|
79
|
+
})
|
|
80
|
+
lines.push(!lines.length ? currentLine : currentLine.trimStart())
|
|
81
|
+
|
|
82
|
+
// Print formatted msg
|
|
83
|
+
lines.forEach((line, idx) => console.info(prefix +(
|
|
84
|
+
idx == 0 ? line // print 1st line unindented
|
|
85
|
+
: ' '.repeat(indent) + line // print subsequent lines indented
|
|
86
|
+
)))
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
helpCmdAndDocURL() {
|
|
91
|
+
console.info(`\n${
|
|
92
|
+
cli.msgs.info_moreHelp}, ${cli.msgs.info_type} ${cli.name} --help' ${
|
|
93
|
+
cli.msgs.info_or} ${cli.msgs.info_visit}\n${
|
|
94
|
+
this.colors.bw}${cli.urls.docs}${this.colors.nc}`
|
|
95
|
+
)
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
version() {
|
|
99
|
+
const { getVer } = require('./pkg')
|
|
100
|
+
this.info(cli.name)
|
|
101
|
+
this.data(`${
|
|
102
|
+
cli.msgs.prefix_globalVer}: ${ getVer('global') || 'none' }\n${
|
|
103
|
+
cli.msgs.prefix_localVer }: ${ getVer('local') || 'none' }`
|
|
104
|
+
)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const log = require('./log')
|
|
2
|
+
|
|
3
|
+
module.exports = {
|
|
4
|
+
getVer(type = 'any') { // or <'global'|'local'>
|
|
5
|
+
let pkgVer
|
|
6
|
+
if (type != 'global')
|
|
7
|
+
try { // get local ver
|
|
8
|
+
const localManifestPath = require('path').resolve(
|
|
9
|
+
process.cwd(), 'node_modules', cli.name, 'package.json')
|
|
10
|
+
pkgVer = require(localManifestPath).version
|
|
11
|
+
} catch (err) { log.debug(`${cli.msgs.error_readingLocalPkgVer}: ${err.message}`) }
|
|
12
|
+
if (type == 'global' || type == 'all' && !pkgVer)
|
|
13
|
+
try { // get global ver
|
|
14
|
+
pkgVer = require('child_process').execSync(
|
|
15
|
+
`npm view ${JSON.stringify(cli.name)} version`
|
|
16
|
+
).toString().trim()
|
|
17
|
+
} catch (err) { log.debug(`${cli.msgs.error_failedToFetchGlobalVer}: ${err.message}`) }
|
|
18
|
+
return pkgVer
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
const fs = require('fs'),
|
|
2
|
+
log = require('./log'),
|
|
3
|
+
path = require('path')
|
|
4
|
+
|
|
5
|
+
;(globalThis.cli ??= {}).config = {}
|
|
6
|
+
|
|
7
|
+
module.exports = {
|
|
8
|
+
configFilename: 'generate-ip.config.mjs',
|
|
9
|
+
|
|
10
|
+
controls: {
|
|
11
|
+
qty: { type: 'param', valType: 'positiveInt', defaultVal: 1, regex: /^--?qu?a?n?ti?t?y(?:=.*|$)/ },
|
|
12
|
+
network: { type: 'param', regex: /^--network(?:=.*|$)/ },
|
|
13
|
+
uiLang: { type: 'param', valType: 'langCode', regex: /^--?ui[-_]?lang(?:=.*|$)/ },
|
|
14
|
+
config: { type: 'param', valType: 'filepath', regex: /^--?config(?:=.*|$)/ },
|
|
15
|
+
ipv6mode: { type: 'flag', mode: true, regex: /^--?(?:ip)?v?6(?:[-_]?mode)?$/ },
|
|
16
|
+
macMode: { type: 'flag', mode: true, regex: /^--?m(?:ac)?(?:[-_]?mode)?$/ },
|
|
17
|
+
quietMode: { type: 'flag', regex: /^--?q(?:uiet)?(?:[-_]?mode)?$/ },
|
|
18
|
+
sequential: { type: 'flag', regex: /^--(?:s|equen(?:tial|ce))$/ },
|
|
19
|
+
init: { type: 'cmd', regex: /^-{0,2}i(?:nit)?$/ },
|
|
20
|
+
help: { type: 'cmd', regex: /^--?h(?:elp)?$/ },
|
|
21
|
+
version: { type: 'cmd', regex: /^--?ve?r?s?i?o?n?$/ }
|
|
22
|
+
},
|
|
23
|
+
|
|
24
|
+
load(ctrlKeys = Object.keys(this.controls)) {
|
|
25
|
+
const inputCtrlKeys = [].concat(ctrlKeys) // force array
|
|
26
|
+
|
|
27
|
+
if (!cli.defaultsSet && !arguments.length) { // init all defaults on arg-less load()
|
|
28
|
+
inputCtrlKeys.forEach(key => {
|
|
29
|
+
const ctrl = this.controls[key] ; if (ctrl.mode) return
|
|
30
|
+
cli.config[key] ??= ctrl.defaultVal ?? ( ctrl.type == 'param' ? '' : false )
|
|
31
|
+
})
|
|
32
|
+
cli.defaultsSet = true
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (!cli.configPathTried) { // init config file path
|
|
36
|
+
const configArg = env.args.find(arg => this.controls.config.regex.test(arg))
|
|
37
|
+
|
|
38
|
+
if (configArg) { // resolve input path, then validate
|
|
39
|
+
if (!/=/.test(configArg))
|
|
40
|
+
log.errorAndExit(`[${configArg}] ${cli.msgs.error_mustIncludePath}`)
|
|
41
|
+
const inputPath = configArg.split('=')[1]
|
|
42
|
+
cli.configPath = path.isAbsolute(inputPath) ? inputPath : path.resolve(process.cwd(), inputPath)
|
|
43
|
+
if (!fs.existsSync(cli.configPath))
|
|
44
|
+
log.configURLandExit(`${cli.msgs.error_configFileNotFound}:`, cli.configPath)
|
|
45
|
+
|
|
46
|
+
} else // auto-discover .config.[mc]?js file
|
|
47
|
+
for (const configExt of ['.mjs', '.cjs', '.js']) {
|
|
48
|
+
const autoPath = path.resolve(process.cwd(), this.configFilename.replace(/\.[^.]+$/, configExt))
|
|
49
|
+
if (fs.existsSync(autoPath)) { cli.configPath = autoPath ; break }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
cli.configPathTried = true
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (cli.configPath) // load from config file
|
|
56
|
+
try {
|
|
57
|
+
const mod = require(cli.configPath), fileConfig = mod?.default ?? mod
|
|
58
|
+
if (!fileConfig || typeof fileConfig != 'object')
|
|
59
|
+
log.configURLandExit(`${cli.msgs.error_invalidConfigFile}.`)
|
|
60
|
+
Object.assign(cli.config, arguments.length ?
|
|
61
|
+
inputCtrlKeys.reduce((acc, key) => fileConfig[key] ? { ...acc, [key]: fileConfig[key] } : acc, {})
|
|
62
|
+
: fileConfig // whole file on arg-less load()
|
|
63
|
+
)
|
|
64
|
+
} catch (err) {
|
|
65
|
+
log.configURLandExit(`${cli.msgs.error_failedToLoadConfigFile}:`, cli.configPath, `\n${err.message}`) }
|
|
66
|
+
|
|
67
|
+
env.args.forEach(arg => { // load from CLI arg (overriding config file loads)
|
|
68
|
+
if (/^[^-]|--?(?:config|debug)/.test(arg) && arg != 'init') return
|
|
69
|
+
const ctrlKey = Object.keys(this.controls).find(key => this.controls[key]?.regex?.test(arg))
|
|
70
|
+
if (!ctrlKey && cli.msgs) log.errorAndExit(`[${arg}] ${cli.msgs.error_notRecognized}.`)
|
|
71
|
+
if (!inputCtrlKeys.includes(ctrlKey)) return // don't process env.args when load() specific keys
|
|
72
|
+
const ctrl = this.controls[ctrlKey]
|
|
73
|
+
if (ctrl.mode) // set cli.config.mode to mode name
|
|
74
|
+
cli.config.mode = ctrlKey.replace(/mode$/i, '').toLowerCase()
|
|
75
|
+
else // init flag/param/cmd cli.config[ctrlKey] val
|
|
76
|
+
cli.config[ctrlKey] = ctrl.type == 'param' ? arg.split('=')[1]?.trim() ?? '' : true
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
this.parseValidateConfig(inputCtrlKeys)
|
|
80
|
+
|
|
81
|
+
return inputCtrlKeys.length == 1 ? cli.config[inputCtrlKeys[0]] : cli.config
|
|
82
|
+
},
|
|
83
|
+
|
|
84
|
+
parseValidateConfig(ctrlKeys = Object.keys(this.controls)) {
|
|
85
|
+
const language = require('./language')
|
|
86
|
+
for (const key of [].concat(ctrlKeys)) {
|
|
87
|
+
const ctrl = this.controls[key], configVal = cli.config[key]
|
|
88
|
+
|
|
89
|
+
if (ctrl.parser && !ctrl.parsed) {
|
|
90
|
+
cli.config[key] = ctrl.parser(configVal) ; ctrl.parsed = true }
|
|
91
|
+
|
|
92
|
+
if (ctrl.valType) ({
|
|
93
|
+
positiveInt() {
|
|
94
|
+
const numVal = parseInt(configVal, 10)
|
|
95
|
+
if (isNaN(numVal) || numVal < 1)
|
|
96
|
+
log.errorAndExit(`[${key}] ${cli.msgs.error_nonPositiveNum}: ${configVal}`)
|
|
97
|
+
cli.config[key] = numVal
|
|
98
|
+
},
|
|
99
|
+
filepath() {
|
|
100
|
+
if (configVal && !fs.existsSync(configVal))
|
|
101
|
+
log.errorAndExit(`[${key}] ${cli.msgs.error_invalidFilepath}: ${configVal}`)
|
|
102
|
+
},
|
|
103
|
+
langCode() {
|
|
104
|
+
if (configVal && !language.validateLangCode(configVal))
|
|
105
|
+
log.errorAndExit(`[${key}] ${cli.msgs.error_invalidLangCode}: ${configVal}`)
|
|
106
|
+
}
|
|
107
|
+
})[ctrl.valType]?.()
|
|
108
|
+
|
|
109
|
+
if (cli.config.sequential) {
|
|
110
|
+
if (!cli.config.network)
|
|
111
|
+
log.errorAndExit(
|
|
112
|
+
`--network ${cli.msgs.error_isRequired} ${cli.msgs.error_whenPassing} --sequential.`)
|
|
113
|
+
else if (cli.config.qty <= 1)
|
|
114
|
+
log.errorAndExit(
|
|
115
|
+
`--qty ${cli.msgs.error_mustBeGreaterThanOne} ${cli.msgs.error_whenPassing} --sequential.`)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
package/docs/README.md
CHANGED
|
@@ -10,12 +10,12 @@
|
|
|
10
10
|
|
|
11
11
|
<a href="#%EF%B8%8F-mit-license">
|
|
12
12
|
<img height=31 src="https://img.shields.io/badge/License-MIT-orange.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge"></a>
|
|
13
|
-
<a href="https://github.com/adamlui/js-utils/releases/tag/generate-ip-2.8.
|
|
14
|
-
<img height=31 src="https://img.shields.io/badge/Latest_Build-2.8.
|
|
13
|
+
<a href="https://github.com/adamlui/js-utils/releases/tag/generate-ip-2.8.2">
|
|
14
|
+
<img height=31 src="https://img.shields.io/badge/Latest_Build-2.8.2-44cc11.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
|
|
15
15
|
<a href="https://www.npmjs.com/package/generate-ip?activeTab=code">
|
|
16
16
|
<img height=31 src="https://img.shields.io/npm/unpacked-size/generate-ip?style=for-the-badge&logo=ebox&logoColor=white&labelColor=464646&color=blue"></a>
|
|
17
|
-
<a href="https://github.com/adamlui/js-utils/blob/generate-ip-2.8.
|
|
18
|
-
<img height=31 src="https://img.shields.io/github/size/adamlui/js-utils/generate-ip/dist/generate-ip.min.js?branch=generate-ip-2.8.
|
|
17
|
+
<a href="https://github.com/adamlui/js-utils/blob/generate-ip-2.8.2/generate-ip/dist/generate-ip.min.js">
|
|
18
|
+
<img height=31 src="https://img.shields.io/github/size/adamlui/js-utils/generate-ip/dist/generate-ip.min.js?branch=generate-ip-2.8.2&label=Minified%20Size&logo=databricks&logoColor=white&labelColor=464646&color=ff69b4&style=for-the-badge"></a>
|
|
19
19
|
<a href="https://sonarcloud.io/component_measures?metric=new_vulnerabilities&id=adamlui_js-utils:generate-ip/src/generate-ip.js">
|
|
20
20
|
<img height=31 src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsonarcloud.io%2Fapi%2Fmeasures%2Fcomponent%3Fcomponent%3Dadamlui_js-utils%3Agenerate-ip%2Fsrc%2Fgenerate-ip.js%26metricKeys%3Dvulnerabilities&query=%24.component.measures.0.value&style=for-the-badge&logo=sonarcloud&logoColor=white&labelColor=464646&label=Vulnerabilities&color=gold"></a>
|
|
21
21
|
<a href="https://github.com/toolleeo/cli-apps#networking">
|
|
@@ -87,14 +87,14 @@ const { ipv4, ipv6, mac } = require('generate-ip')
|
|
|
87
87
|
#### <> HTML script tag:
|
|
88
88
|
|
|
89
89
|
```html
|
|
90
|
-
<script src="https://cdn.jsdelivr.net/npm/generate-ip@2.8.
|
|
90
|
+
<script src="https://cdn.jsdelivr.net/npm/generate-ip@2.8.2/dist/generate-ip.min.js"></script>
|
|
91
91
|
```
|
|
92
92
|
|
|
93
93
|
#### ES6:
|
|
94
94
|
|
|
95
95
|
```js
|
|
96
96
|
(async () => {
|
|
97
|
-
await import('https://cdn.jsdelivr.net/npm/generate-ip@2.8.
|
|
97
|
+
await import('https://cdn.jsdelivr.net/npm/generate-ip@2.8.2/dist/generate-ip.min.js')
|
|
98
98
|
// Your code here...
|
|
99
99
|
})()
|
|
100
100
|
```
|
|
@@ -103,7 +103,7 @@ const { ipv4, ipv6, mac } = require('generate-ip')
|
|
|
103
103
|
|
|
104
104
|
```js
|
|
105
105
|
...
|
|
106
|
-
// @require https://cdn.jsdelivr.net/npm/generate-ip@2.8.
|
|
106
|
+
// @require https://cdn.jsdelivr.net/npm/generate-ip@2.8.2/dist/generate-ip.min.js
|
|
107
107
|
// ==/UserScript==
|
|
108
108
|
|
|
109
109
|
// Your code here...
|
|
@@ -111,7 +111,7 @@ const { ipv4, ipv6, mac } = require('generate-ip')
|
|
|
111
111
|
|
|
112
112
|
<br>
|
|
113
113
|
|
|
114
|
-
๐ **Note:** To always import the latest version (not recommended in production!) remove the `@2.8.
|
|
114
|
+
๐ **Note:** To always import the latest version (not recommended in production!) remove the `@2.8.2` version tag from the jsDelivr URL: `https://cdn.jsdelivr.net/npm/generate-ip/dist/generate-ip.min.js`
|
|
115
115
|
|
|
116
116
|
<br>
|
|
117
117
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "generate-ip",
|
|
3
|
-
"version": "2.8.
|
|
3
|
+
"version": "2.8.2",
|
|
4
4
|
"description": "Randomly generate, format, and validate IPv4 + IPv6 + MAC addresses.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Adam Lui",
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
"doc": "./docs"
|
|
39
39
|
},
|
|
40
40
|
"scripts": {
|
|
41
|
+
"dev": "npm run build && npm i -g",
|
|
41
42
|
"build": "node utils/build",
|
|
42
43
|
"build:js": "node utils/build --js",
|
|
43
44
|
"build:data": "node utils/build --data",
|
package/dist/cli/index.min.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* ยฉ 2024โ2026 Adam Lui & contributors under the MIT license.
|
|
4
|
-
* Source: https://github.com/adamlui/js-utils/tree/main/generate-ip/src
|
|
5
|
-
* Documentation: https://github.com/adamlui/js-utils/tree/main/generate-ip/docs
|
|
6
|
-
*/
|
|
7
|
-
(async()=>{globalThis.env={args:process.argv.slice(2),devMode:/[\\/]src(?:[\\/]|$)/i.test(__dirname)},env.debugMode=env.args.some(e=>/^--?debug(?:-?mode)?$/.test(e)),env.modExt=`${env.devMode?"":".min"}.js`;var e=require("node-clipboardy"),i=require("../generate-ip"+env.modExt),n=require("./lib/init"+env.modExt),o=require("./lib/log"+env.modExt);return await n.cli(),cli.config.init?n.configFile():cli.config.help?o.help():cli.config.version?o.version():(n={qty:cli.config.qty,sequential:cli.config.sequential,network:cli.config.network,verbose:!cli.config.quietMode},e.writeSync([].concat(i[cli.config.mode||"ipv4"].generate(n)).join("\n")),void o.ifNotQuiet(`
|
|
8
|
-
${cli.msgs.info_copyingToClip}...`))})();
|
package/dist/cli/lib/data.min.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ยฉ 2024โ2026 Adam Lui & contributors under the MIT license.
|
|
3
|
-
* Source: https://github.com/adamlui/js-utils/tree/main/generate-ip/src
|
|
4
|
-
* Documentation: https://github.com/adamlui/js-utils/tree/main/generate-ip/docs
|
|
5
|
-
*/
|
|
6
|
-
module.exports={atomicWrite(e,r,t="utf8"){var n=require("fs"),a=require("path"),a=a.join(a.dirname(e),`.${a.basename(e)}.tmp`);n.writeFileSync(a,r,t),n.renameSync(a,e)},fetch(n){return"undefined"==typeof fetch?new Promise((t,e)=>{var r=n.match(/^([^:]+):\/\//)[1];/^https?$/.test(r)||e(new Error(cli.msgs.error_invalidURL+".")),require(r).get(n,e=>{let r="";e.on("data",e=>r+=e),e.on("end",()=>t({json:()=>JSON.parse(r)}))}).on("error",e)}):fetch(n)},flatten(e,{key:r="message"}={}){var t,n={};for(t in e)n[t]="object"==typeof e[t]&&r in e[t]?e[t][r]:e[t];return n}};
|
package/dist/cli/lib/init.min.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ยฉ 2024โ2026 Adam Lui & contributors under the MIT license.
|
|
3
|
-
* Source: https://github.com/adamlui/js-utils/tree/main/generate-ip/src
|
|
4
|
-
* Documentation: https://github.com/adamlui/js-utils/tree/main/generate-ip/docs
|
|
5
|
-
*/
|
|
6
|
-
let language=require("./language"+env.modExt),log=require("./log"+env.modExt),settings=require("./settings"+env.modExt),dataPath="../../"+(env.devMode?"../":"data/");module.exports={async cli(){Object.assign(globalThis.cli??={},require(dataPath+"package-data.json")),cli.lang=settings.load("uiLang")||(env.debugMode?language.generateRandomLang({excludes:["en"]}):language.getSysLang()),cli.msgs=await language.getMsgs(cli.lang),cli.urls.cliDocs||=cli.urls.docs+"/#-command-line-usage",settings.load()},async configFile(e=settings.configFilename){var t=require("fs"),a=require("path"),i={target:a.resolve(process.cwd(),e)};if(t.existsSync(i.target))return log.warn(cli.msgs.warn_configFileExists+":",i.target);if(t.existsSync(i.src=a.resolve(__dirname,""+dataPath+e)))t.copyFileSync(i.src,i.target);else{a=require("./jsdelivr"+env.modExt).pkgVerURL+`/${e}/`;log.data(cli.msgs.info_fetchingRemoteConfigFrom+` ${a}...`);try{var s=require("./data"+env.modExt),g=await s.fetch(a);if(!g.ok)return log.warn(`${cli.msgs.warn_remoteConfigNotFound}: ${a} (${g.status})`);s.atomicWrite(i.target,await g.text())}catch(e){return log.warn(cli.msgs.warn_remoteConfigFailed+`: ${a} `+e.message)}}log.success(`${cli.msgs.info_configFileCreated}: ${i.target}\n`),log.tip(cli.msgs.tip_editToSetDefaults+"."),log.tip(cli.msgs.tip_cliArgsPrioritized+".")}};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ยฉ 2024โ2026 Adam Lui & contributors under the MIT license.
|
|
3
|
-
* Source: https://github.com/adamlui/js-utils/tree/main/generate-ip/src
|
|
4
|
-
* Documentation: https://github.com/adamlui/js-utils/tree/main/generate-ip/docs
|
|
5
|
-
*/
|
|
6
|
-
module.exports={pkgVerURL(e){e||=cli.version||=require("./pkg"+env.modExt).getVer("local")||"none";e=/^\d+\.\d+\.\d+$/.test(e)?cli.name+"-"+e:"latest";return cli.urls.jsdelivr+`@${e}/`+cli.name},commitURL(e="latest"){return cli.urls.jsdelivr+`@${e}/`+cli.name}};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ยฉ 2024โ2026 Adam Lui & contributors under the MIT license.
|
|
3
|
-
* Source: https://github.com/adamlui/js-utils/tree/main/generate-ip/src
|
|
4
|
-
* Documentation: https://github.com/adamlui/js-utils/tree/main/generate-ip/docs
|
|
5
|
-
*/
|
|
6
|
-
let data=require("./data"+env.modExt),log=require("./log"+env.modExt);module.exports={formatCode(e){return e.replace(/([a-z]{2,8})[-_]([a-z]{2})/i,(e,r,t)=>r.toLowerCase()+"_"+t.toUpperCase())},generateRandomLang({includes:e=[],excludes:r=[]}={}){let a=require("fs"),s=require("path"),t=e.length?e:(()=>{var e=s.join(__dirname,"..",".cache"),r=s.join(e,"locales.json");if(a.existsSync(r))try{return JSON.parse(a.readFileSync(r,"utf8"))}catch(e){}var t=s.resolve(process.cwd(),"_locales");return a.existsSync(t)?(t=a.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).filter(e=>/^\w{2}[-_]?\w{0,2}$/.test(e)),a.mkdirSync(e,{recursive:!0}),data.atomicWrite(r,JSON.stringify(t,null,2)),t):["en"]})(),n=new Set(r),l="en";return(t=t.filter(e=>!n.has(e))).length&&(l=t[Math.floor(Math.random()*t.length)]),log.debug(`Random language: ${l}
|
|
7
|
-
`),l},async getMsgs(a="en"){if(a=module.exports.formatCode(a),env.msgs&&a==cli.lang)return env.msgs;let e=data.flatten(require(`../../${env.devMode?"../_locales/en/":"data/"}messages.json`));if(!a.startsWith("en")){var s=require("./jsdelivr"+env.modExt).commitURL(cli.commitHashes.locales)+"/_locales/";let r=s+a+"/messages.json",t=0;for(;t<3;)try{e=data.flatten(await(await data.fetch(r)).json());break}catch(e){if(3<=++t)break;log.debug(r=a.includes("-")&&1==t?r.replace(/([^_]*)_[^/]*(\/.*)/,"$1$2"):s+"en/messages.json")}}return e},getSysLang(){try{var e;return"win32"==process.platform?require("child_process").execSync("(Get-Culture).TwoLetterISOLanguageName",{shell:"powershell",encoding:"utf-8"}).trim():((e=process.env).LANG||e.LANGUAGE||e.LC_ALL||e.LC_MESSAGES||e.LC_NAME).split(".")[0]}catch(e){return log.error(cli.msgs.error_failedToFetchSysLang+":",e.message),"en"}},validateLangCode(e){return"string"==typeof e&&/^[a-z]{2,8}(?:[-_][a-z]{2,3})?$/i.test(e)}};
|
package/dist/cli/lib/log.min.js
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ยฉ 2024โ2026 Adam Lui & contributors under the MIT license.
|
|
3
|
-
* Source: https://github.com/adamlui/js-utils/tree/main/generate-ip/src
|
|
4
|
-
* Documentation: https://github.com/adamlui/js-utils/tree/main/generate-ip/docs
|
|
5
|
-
*/
|
|
6
|
-
module.exports={colors:{nc:"[0m",br:"[1;91m",by:"[1;33m",bo:"[38;5;214m",bg:"[1;92m",bw:"[1;97m",gry:"[90m",blk:"[30m",tlBG:"[106m"},configURL(){this.info(`
|
|
7
|
-
${cli.msgs.info_exampleValidConfigFile}: `+cli.urls.config)},configURLandExit(...s){this.error(...s),this.configURL(),process.exit(1)},data(s){console.log(`
|
|
8
|
-
`+this.colors.bw+s+this.colors.nc)},debug(s){env.debugMode&&console.debug(`
|
|
9
|
-
${this.colors.bo}DEBUG:`,s,this.colors.nc,"\n")},dim(s){console.log(""+this.colors.gry+s+this.colors.nc)},error(...s){console.error(`
|
|
10
|
-
${this.colors.br}ERROR:`,...s,this.colors.nc)},errorAndExit(...s){this.error(...s),this.helpCmdAndDocURL(),process.exit(1)},ifNotQuiet(s){cli.config.quietMode||console.info(s)},info(s){console.info(`
|
|
11
|
-
`+this.colors.by+s+this.colors.nc)},tip(s){console.info(this.colors.by+"TIP: "+s+this.colors.nc)},success(s){console.log(`
|
|
12
|
-
`+this.colors.bg+s+this.colors.nc)},warn(...s){console.warn(`
|
|
13
|
-
${this.colors.bo}WARNING:`,...s,this.colors.nc)},help(s=["header","usage","params","flags","cmds"]){cli.prefix=""+this.colors.tlBG+this.colors.blk+`[30m ${cli.name} ${this.colors.nc} `;let o={header:[`
|
|
14
|
-
โ ${cli.prefix}${cli.msgs.appCopyright}.`,""+cli.prefix+cli.msgs.prefix_source+": "+cli.urls.src],usage:[`
|
|
15
|
-
${this.colors.bw}o ${cli.msgs.helpSection_usage}:`+this.colors.nc,` ${this.colors.bw}ยป `+this.colors.bg+cli.cmdFormat+this.colors.nc],params:[`
|
|
16
|
-
${this.colors.bw}o ${cli.msgs.helpSection_params}:`+this.colors.nc,` --qty=n ${cli.msgs.optionDesc_qty}.`,` --ui-lang="code" ${cli.msgs.optionDesc_uiLang}.`,` --config="path/to/file" ${cli.msgs.optionDesc_config}.`,` --network="address" ${cli.msgs.optionDesc_network}.`],flags:[`
|
|
17
|
-
${this.colors.bw}o ${cli.msgs.helpSection_flags}:`+this.colors.nc,` -6, --ipv6 ${cli.msgs.optionDesc_ipv6}.`,` -m, --mac ${cli.msgs.optionDesc_mac}.`,` -s, --sequential ${cli.msgs.optionDesc_sequential}.`,` -q, --quiet ${cli.msgs.optionDesc_quiet}.`],cmds:[`
|
|
18
|
-
${this.colors.bw}o ${cli.msgs.helpSection_cmds}:`+this.colors.nc,` -i, --init ${cli.msgs.optionDesc_init}.`,` -h, --help ${cli.msgs.optionDesc_help}.`,` -v, --version ${cli.msgs.optionDesc_version}.`]};s.forEach(t=>o[t]?.forEach(o=>{{var e=/header|usage/.test(t)?1:29;let i=process.stdout.columns||80,s=o.match(/\S+|\s+/g),c=[],l="";s.forEach(s=>{var o=i-(c.length?e:0);l.length+"| ".length+s.length>o&&(c.push(c.length?l.trimStart():l),l=""),l+=s}),c.push(c.length?l.trimStart():l),c.forEach((s,o)=>console.info("| "+(0==o?s:" ".repeat(e)+s)))}})),console.info(`
|
|
19
|
-
${cli.msgs.info_moreHelp}, ${cli.msgs.info_visit}: `+this.colors.bw+cli.urls.cliDocs+this.colors.nc)},helpCmdAndDocURL(){console.info(`
|
|
20
|
-
${cli.msgs.info_moreHelp}, ${cli.msgs.info_type} ${cli.name} --help' ${cli.msgs.info_or} ${cli.msgs.info_visit}
|
|
21
|
-
`+this.colors.bw+cli.urls.docs+this.colors.nc)},version(){var s=require("./pkg"+env.modExt).getVer;this.info(cli.name),this.data(`${cli.msgs.prefix_globalVer}: ${s("global")||"none"}
|
|
22
|
-
${cli.msgs.prefix_localVer}: `+(s("local")||"none"))}};
|
package/dist/cli/lib/pkg.min.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ยฉ 2024โ2026 Adam Lui & contributors under the MIT license.
|
|
3
|
-
* Source: https://github.com/adamlui/js-utils/tree/main/generate-ip/src
|
|
4
|
-
* Documentation: https://github.com/adamlui/js-utils/tree/main/generate-ip/docs
|
|
5
|
-
*/
|
|
6
|
-
let log=require("./log"+env.modExt);module.exports={getVer(e="any"){let r;if("global"!=e)try{var l=require("path").resolve(process.cwd(),"node_modules",cli.name,"package.json");r=require(l).version}catch(e){log.debug(cli.msgs.error_readingLocalPkgVer+": "+e.message)}if("global"==e||"all"==e&&!r)try{r=require("child_process").execSync(`npm view ${JSON.stringify(cli.name)} version`).toString().trim()}catch(e){log.debug(cli.msgs.error_failedToFetchGlobalVer+": "+e.message)}return r}};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ยฉ 2024โ2026 Adam Lui & contributors under the MIT license.
|
|
3
|
-
* Source: https://github.com/adamlui/js-utils/tree/main/generate-ip/src
|
|
4
|
-
* Documentation: https://github.com/adamlui/js-utils/tree/main/generate-ip/docs
|
|
5
|
-
*/
|
|
6
|
-
let fs=require("fs"),log=require("./log"+env.modExt),path=require("path");(globalThis.cli??={}).config={},module.exports={configFilename:"generate-ip.config.mjs",controls:{qty:{type:"param",valType:"positiveInt",defaultVal:1,regex:/^--?qu?a?n?ti?t?y(?:=.*|$)/},network:{type:"param",regex:/^--network(?:=.*|$)/},uiLang:{type:"param",valType:"langCode",regex:/^--?ui[-_]?lang(?:=.*|$)/},config:{type:"param",valType:"filepath",regex:/^--?config(?:=.*|$)/},ipv6mode:{type:"flag",mode:!0,regex:/^--?(?:ip)?v?6(?:[-_]?mode)?$/},macMode:{type:"flag",mode:!0,regex:/^--?m(?:ac)?(?:[-_]?mode)?$/},quietMode:{type:"flag",regex:/^--?q(?:uiet)?(?:[-_]?mode)?$/},sequential:{type:"flag",regex:/^--(?:s|equen(?:tial|ce))$/},init:{type:"cmd",regex:/^-{0,2}i(?:nit)?$/},help:{type:"cmd",regex:/^--?h(?:elp)?$/},version:{type:"cmd",regex:/^--?ve?r?s?i?o?n?$/}},load(e=Object.keys(this.controls)){let r=[].concat(e);if(cli.defaultsSet||arguments.length||(r.forEach(e=>{var i=this.controls[e];i.mode||(cli.config[e]??=i.defaultVal??("param"==i.type&&""))}),cli.defaultsSet=!0),!cli.configPathTried){e=env.args.find(e=>this.controls.config.regex.test(e));if(e){/=/.test(e)||log.errorAndExit(`[${e}] `+cli.msgs.error_mustIncludePath);e=e.split("=")[1];cli.configPath=path.isAbsolute(e)?e:path.resolve(process.cwd(),e),fs.existsSync(cli.configPath)||log.configURLandExit(cli.msgs.error_configFileNotFound+":",cli.configPath)}else for(var i of[".mjs",".cjs",".js"]){i=path.resolve(process.cwd(),this.configFilename.replace(/\.[^.]+$/,i));if(fs.existsSync(i)){cli.configPath=i;break}}cli.configPathTried=!0}if(cli.configPath)try{let e=require(cli.configPath),o=e?.default??e;o&&"object"==typeof o||log.configURLandExit(cli.msgs.error_invalidConfigFile+"."),Object.assign(cli.config,arguments.length?r.reduce((e,i)=>o[i]?{...e,[i]:o[i]}:e,{}):o)}catch(e){log.configURLandExit(cli.msgs.error_failedToLoadConfigFile+":",cli.configPath,`
|
|
7
|
-
`+e.message)}return env.args.forEach(i=>{var e,o;/^[^-]|--?(?:config|debug)/.test(i)&&"init"!=i||(!(e=Object.keys(this.controls).find(e=>this.controls[e]?.regex?.test(i)))&&cli.msgs&&log.errorAndExit(`[${i}] ${cli.msgs.error_notRecognized}.`),r.includes(e)&&((o=this.controls[e]).mode?cli.config.mode=e.replace(/mode$/i,"").toLowerCase():cli.config[e]="param"!=o.type||(i.split("=")[1]?.trim()??"")))}),this.parseValidateConfig(r),1==r.length?cli.config[r[0]]:cli.config},parseValidateConfig(e=Object.keys(this.controls)){let r=require("./language"+env.modExt);for(let o of[].concat(e)){let e=this.controls[o],i=cli.config[o];e.parser&&!e.parsed&&(cli.config[o]=e.parser(i),e.parsed=!0),e.valType&&{positiveInt(){var e=parseInt(i,10);(isNaN(e)||e<1)&&log.errorAndExit(`[${o}] ${cli.msgs.error_nonPositiveNum}: `+i),cli.config[o]=e},filepath(){i&&!fs.existsSync(i)&&log.errorAndExit(`[${o}] ${cli.msgs.error_invalidFilepath}: `+i)},langCode(){i&&!r.validateLangCode(i)&&log.errorAndExit(`[${o}] ${cli.msgs.error_invalidLangCode}: `+i)}}[e.valType]?.(),cli.config.sequential&&(cli.config.network?cli.config.qty<=1&&log.errorAndExit(`--qty ${cli.msgs.error_mustBeGreaterThanOne} ${cli.msgs.error_whenPassing} --sequential.`):log.errorAndExit(`--network ${cli.msgs.error_isRequired} ${cli.msgs.error_whenPassing} --sequential.`))}}};
|