UNPKG

dns-setting

Version:

dns management: query, modify, shield corresponding domain name resolution

1,527 lines (1,510 loc) 44.9 kB
#!/usr/bin/env node 'use strict'; var assert = require('node:assert'); var node_child_process = require('node:child_process'); var node_async_hooks = require('node:async_hooks'); var node_util = require('node:util'); var process$1 = require('node:process'); var os = require('node:os'); var tty = require('node:tty'); var which = require('which'); var psTreeModule = require('ps-tree'); var fs = require('node:fs'); var path = require('node:path'); var merge2 = require('merge2'); var fastGlob = require('fast-glob'); var dirGlob = require('dir-glob'); var gitIgnore = require('ignore'); var node_url = require('node:url'); var Stream = require('node:stream'); var minimist = require('minimist'); require('node:readline'); require('fs-extra'); require('yaml'); require('fs'); const ANSI_BACKGROUND_OFFSET = 10; const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; const styles$1 = { modifier: { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], blackBright: [90, 39], gray: [90, 39], grey: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgGray: [100, 49], bgGrey: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], }, }; Object.keys(styles$1.modifier); const foregroundColorNames = Object.keys(styles$1.color); const backgroundColorNames = Object.keys(styles$1.bgColor); [...foregroundColorNames, ...backgroundColorNames]; function assembleStyles() { const codes = new Map(); for (const [groupName, group] of Object.entries(styles$1)) { for (const [styleName, style] of Object.entries(group)) { styles$1[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m`, }; group[styleName] = styles$1[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles$1, groupName, { value: group, enumerable: false, }); } Object.defineProperty(styles$1, 'codes', { value: codes, enumerable: false, }); styles$1.color.close = '\u001B[39m'; styles$1.bgColor.close = '\u001B[49m'; styles$1.color.ansi = wrapAnsi16(); styles$1.color.ansi256 = wrapAnsi256(); styles$1.color.ansi16m = wrapAnsi16m(); styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); Object.defineProperties(styles$1, { rgbToAnsi256: { value(red, green, blue) { if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round(((red - 8) / 247) * 24) + 232; } return 16 + (36 * Math.round(red / 255 * 5)) + (6 * Math.round(green / 255 * 5)) + Math.round(blue / 255 * 5); }, enumerable: false, }, hexToRgb: { value(hex) { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map(character => character + character).join(''); } const integer = Number.parseInt(colorString, 16); return [ (integer >> 16) & 0xFF, (integer >> 8) & 0xFF, integer & 0xFF, ]; }, enumerable: false, }, hexToAnsi256: { value: hex => styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)), enumerable: false, }, ansi256ToAnsi: { value(code) { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = (((code - 232) * 10) + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = (remainder % 6) / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false, }, rgbToAnsi: { value: (red, green, blue) => styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)), enumerable: false, }, hexToAnsi: { value: hex => styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)), enumerable: false, }, }); return styles$1; } const ansiStyles = assembleStyles(); function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process$1.argv) { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); } const {env} = process$1; let flagForceColor; if ( hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never') ) { flagForceColor = 0; } else if ( hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always') ) { flagForceColor = 1; } function envForceColor() { if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { return 1; } if (env.FORCE_COLOR === 'false') { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3, }; } function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== undefined) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if (sniffFlags) { if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } } if ('TF_BUILD' in env && 'AGENT_NAME' in env) { return 1; } if (haveStream && !streamIsTTY && forceColor === undefined) { return 0; } const min = forceColor || 0; if (env.TERM === 'dumb') { return min; } if (process$1.platform === 'win32') { const osRelease = os.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10_586 ) { return Number(osRelease[2]) >= 14_931 ? 3 : 2; } return 1; } if ('CI' in env) { if ('GITHUB_ACTIONS' in env) { return 3; } if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if (env.TERM === 'xterm-kitty') { return 3; } if ('TERM_PROGRAM' in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': { return version >= 3 ? 3 : 2; } case 'Apple_Terminal': { return 2; } } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } return min; } function createSupportsColor(stream, options = {}) { const level = _supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options, }); return translateLevel(level); } const supportsColor = { stdout: createSupportsColor({isTTY: tty.isatty(1)}), stderr: createSupportsColor({isTTY: tty.isatty(2)}), }; function stringReplaceAll(string, substring, replacer) { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.slice(endIndex, index) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } const {stdout: stdoutColor, stderr: stderrColor} = supportsColor; const GENERATOR = Symbol('GENERATOR'); const STYLER = Symbol('STYLER'); const IS_EMPTY = Symbol('IS_EMPTY'); const levelMapping = [ 'ansi', 'ansi', 'ansi256', 'ansi16m', ]; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { throw new Error('The `level` option should be an integer from 0 to 3'); } const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; const chalkFactory = options => { const chalk = (...strings) => strings.join(' '); applyOptions(chalk, options); Object.setPrototypeOf(chalk, createChalk.prototype); return chalk; }; function createChalk(options) { return chalkFactory(options); } Object.setPrototypeOf(createChalk.prototype, Function.prototype); for (const [styleName, style] of Object.entries(ansiStyles)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]); Object.defineProperty(this, styleName, {value: builder}); return builder; }, }; } styles.visible = { get() { const builder = createBuilder(this, this[STYLER], true); Object.defineProperty(this, 'visible', {value: builder}); return builder; }, }; const getModelAnsi = (model, level, type, ...arguments_) => { if (model === 'rgb') { if (level === 'ansi16m') { return ansiStyles[type].ansi16m(...arguments_); } if (level === 'ansi256') { return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_)); } return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_)); } if (model === 'hex') { return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_)); } return ansiStyles[type][model](...arguments_); }; const usedModels = ['rgb', 'hex', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]); return createBuilder(this, styler, this[IS_EMPTY]); }; }, }; const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]); return createBuilder(this, styler, this[IS_EMPTY]); }; }, }; } const proto = Object.defineProperties(() => {}, { ...styles, level: { enumerable: true, get() { return this[GENERATOR].level; }, set(level) { this[GENERATOR].level = level; }, }, }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent, }; }; const createBuilder = (self, _styler, _isEmpty) => { const builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); Object.setPrototypeOf(builder, proto); builder[GENERATOR] = self; builder[STYLER] = _styler; builder[IS_EMPTY] = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self[IS_EMPTY] ? '' : string; } let styler = self[STYLER]; if (styler === undefined) { return string; } const {openAll, closeAll} = styler; if (string.includes('\u001B')) { while (styler !== undefined) { string = stringReplaceAll(string, styler.close, styler.open); styler = styler.parent; } } const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; Object.defineProperties(createChalk.prototype, styles); const chalk = createChalk(); createChalk({level: stderrColor ? stderrColor.level : 0}); const psTree = node_util.promisify(psTreeModule); function noop() { } function quote(arg) { if (/^[a-z0-9/_.\-@:=]+$/i.test(arg) || arg === '') { return arg; } return (`$'` + arg .replace(/\\/g, '\\\\') .replace(/'/g, "\\'") .replace(/\f/g, '\\f') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/\t/g, '\\t') .replace(/\v/g, '\\v') .replace(/\0/g, '\\0') + `'`); } function quotePowerShell(arg) { if (/^[a-z0-9/_.\-]+$/i.test(arg) || arg === '') { return arg; } return `'` + arg.replace(/'/g, "''") + `'`; } function exitCodeInfo(exitCode) { return { 2: 'Misuse of shell builtins', 126: 'Invoked command cannot execute', 127: 'Command not found', 128: 'Invalid exit argument', 129: 'Hangup', 130: 'Interrupt', 131: 'Quit and dump core', 132: 'Illegal instruction', 133: 'Trace/breakpoint trap', 134: 'Process aborted', 135: 'Bus error: "access to undefined portion of memory object"', 136: 'Floating point exception: "erroneous arithmetic operation"', 137: 'Kill (terminate immediately)', 138: 'User-defined 1', 139: 'Segmentation violation', 140: 'User-defined 2', 141: 'Write to pipe with no one reading', 142: 'Signal raised by alarm', 143: 'Termination (request to terminate)', 145: 'Child process terminated, stopped (or continued*)', 146: 'Continue if stopped', 147: 'Stop executing temporarily', 148: 'Terminal stop signal', 149: 'Background process attempting to read from tty ("in")', 150: 'Background process attempting to write to tty ("out")', 151: 'Urgent data available on socket', 152: 'CPU time limit exceeded', 153: 'File size limit exceeded', 154: 'Signal raised by timer counting virtual time: "virtual timer expired"', 155: 'Profiling timer expired', 157: 'Pollable event', 159: 'Bad syscall', }[exitCode || -1]; } function errnoMessage(errno) { if (errno === undefined) { return 'Unknown error'; } return ({ 0: 'Success', 1: 'Not super-user', 2: 'No such file or directory', 3: 'No such process', 4: 'Interrupted system call', 5: 'I/O error', 6: 'No such device or address', 7: 'Arg list too long', 8: 'Exec format error', 9: 'Bad file number', 10: 'No children', 11: 'No more processes', 12: 'Not enough core', 13: 'Permission denied', 14: 'Bad address', 15: 'Block device required', 16: 'Mount device busy', 17: 'File exists', 18: 'Cross-device link', 19: 'No such device', 20: 'Not a directory', 21: 'Is a directory', 22: 'Invalid argument', 23: 'Too many open files in system', 24: 'Too many open files', 25: 'Not a typewriter', 26: 'Text file busy', 27: 'File too large', 28: 'No space left on device', 29: 'Illegal seek', 30: 'Read only file system', 31: 'Too many links', 32: 'Broken pipe', 33: 'Math arg out of domain of func', 34: 'Math result not representable', 35: 'File locking deadlock error', 36: 'File or path name too long', 37: 'No record locks available', 38: 'Function not implemented', 39: 'Directory not empty', 40: 'Too many symbolic links', 42: 'No message of desired type', 43: 'Identifier removed', 44: 'Channel number out of range', 45: 'Level 2 not synchronized', 46: 'Level 3 halted', 47: 'Level 3 reset', 48: 'Link number out of range', 49: 'Protocol driver not attached', 50: 'No CSI structure available', 51: 'Level 2 halted', 52: 'Invalid exchange', 53: 'Invalid request descriptor', 54: 'Exchange full', 55: 'No anode', 56: 'Invalid request code', 57: 'Invalid slot', 59: 'Bad font file fmt', 60: 'Device not a stream', 61: 'No data (for no delay io)', 62: 'Timer expired', 63: 'Out of streams resources', 64: 'Machine is not on the network', 65: 'Package not installed', 66: 'The object is remote', 67: 'The link has been severed', 68: 'Advertise error', 69: 'Srmount error', 70: 'Communication error on send', 71: 'Protocol error', 72: 'Multihop attempted', 73: 'Cross mount point (not really error)', 74: 'Trying to read unreadable message', 75: 'Value too large for defined data type', 76: 'Given log. name not unique', 77: 'f.d. invalid for this operation', 78: 'Remote address changed', 79: 'Can access a needed shared lib', 80: 'Accessing a corrupted shared lib', 81: '.lib section in a.out corrupted', 82: 'Attempting to link in too many libs', 83: 'Attempting to exec a shared library', 84: 'Illegal byte sequence', 86: 'Streams pipe error', 87: 'Too many users', 88: 'Socket operation on non-socket', 89: 'Destination address required', 90: 'Message too long', 91: 'Protocol wrong type for socket', 92: 'Protocol not available', 93: 'Unknown protocol', 94: 'Socket type not supported', 95: 'Not supported', 96: 'Protocol family not supported', 97: 'Address family not supported by protocol family', 98: 'Address already in use', 99: 'Address not available', 100: 'Network interface is not configured', 101: 'Network is unreachable', 102: 'Connection reset by network', 103: 'Connection aborted', 104: 'Connection reset by peer', 105: 'No buffer space available', 106: 'Socket is already connected', 107: 'Socket is not connected', 108: "Can't send after socket shutdown", 109: 'Too many references', 110: 'Connection timed out', 111: 'Connection refused', 112: 'Host is down', 113: 'Host is unreachable', 114: 'Socket already connected', 115: 'Connection already in progress', 116: 'Stale file handle', 122: 'Quota exceeded', 123: 'No medium (in tape drive)', 125: 'Operation canceled', 130: 'Previous owner died', 131: 'State not recoverable', }[-errno] || 'Unknown error'); } function parseDuration(d) { if (typeof d == 'number') { if (isNaN(d) || d < 0) throw new Error(`Invalid duration: "${d}".`); return d; } else if (/\d+s/.test(d)) { return +d.slice(0, -1) * 1000; } else if (/\d+ms/.test(d)) { return +d.slice(0, -2); } throw new Error(`Unknown duration: "${d}".`); } function formatCmd(cmd) { if (cmd == undefined) return chalk.grey('undefined'); const chars = [...cmd]; let out = '$ '; let buf = ''; let ch; let state = root; let wordCount = 0; while (state) { ch = chars.shift() || 'EOF'; if (ch == '\n') { out += style(state, buf) + '\n> '; buf = ''; continue; } const next = ch == 'EOF' ? undefined : state(); if (next != state) { out += style(state, buf); buf = ''; } state = next == root ? next() : next; buf += ch; } function style(state, s) { if (s == '') return ''; if (reservedWords.includes(s)) { return chalk.cyanBright(s); } if (state == word && wordCount == 0) { wordCount++; return chalk.greenBright(s); } if (state == syntax) { wordCount = 0; return chalk.cyanBright(s); } if (state == dollar) return chalk.yellowBright(s); if (state?.name.startsWith('str')) return chalk.yellowBright(s); return s; } function isSyntax(ch) { return '()[]{}<>;:+|&='.includes(ch); } function root() { if (/\s/.test(ch)) return space; if (isSyntax(ch)) return syntax; if (/[$]/.test(ch)) return dollar; if (/["]/.test(ch)) return strDouble; if (/[']/.test(ch)) return strSingle; return word; } function space() { if (/\s/.test(ch)) return space; return root; } function word() { if (/[0-9a-z/_.]/i.test(ch)) return word; return root; } function syntax() { if (isSyntax(ch)) return syntax; return root; } function dollar() { if (/[']/.test(ch)) return str; return root; } function str() { if (/[']/.test(ch)) return strEnd; if (/[\\]/.test(ch)) return strBackslash; return str; } function strBackslash() { return strEscape; } function strEscape() { return str; } function strDouble() { if (/["]/.test(ch)) return strEnd; return strDouble; } function strSingle() { if (/[']/.test(ch)) return strEnd; return strSingle; } function strEnd() { return root; } return out + '\n'; } const reservedWords = [ 'if', 'then', 'else', 'elif', 'fi', 'case', 'esac', 'for', 'select', 'while', 'until', 'do', 'done', 'in', ]; const processCwd = Symbol('processCwd'); const storage = new node_async_hooks.AsyncLocalStorage(); const hook = node_async_hooks.createHook({ init: syncCwd, before: syncCwd, promiseResolve: syncCwd, after: syncCwd, destroy: syncCwd, }); hook.enable(); const defaults = { [processCwd]: process.cwd(), verbose: true, env: process.env, shell: true, prefix: '', quote: () => { throw new Error('No quote function is defined: https://ï.at/no-quote-func'); }, spawn: node_child_process.spawn, log, }; try { defaults.shell = which.sync('bash'); defaults.prefix = 'set -euo pipefail;'; defaults.quote = quote; } catch (err) { if (process.platform == 'win32') { defaults.shell = which.sync('powershell.exe'); defaults.quote = quotePowerShell; } } function getStore() { return storage.getStore() || defaults; } const $ = new Proxy(function (pieces, ...args) { const from = new Error().stack.split(/^\s*at\s/m)[2].trim(); if (pieces.some((p) => p == undefined)) { throw new Error(`Malformed command at ${from}`); } let resolve, reject; const promise = new ProcessPromise((...args) => ([resolve, reject] = args)); let cmd = pieces[0], i = 0; while (i < args.length) { let s; if (Array.isArray(args[i])) { s = args[i].map((x) => $.quote(substitute(x))).join(' '); } else { s = $.quote(substitute(args[i])); } cmd += s + pieces[++i]; } promise._bind(cmd, from, resolve, reject, getStore()); setImmediate(() => promise.isHalted || promise.run()); return promise; }, { set(_, key, value) { const target = key in Function.prototype ? _ : getStore(); Reflect.set(target, key, value); return true; }, get(_, key) { const target = key in Function.prototype ? _ : getStore(); return Reflect.get(target, key); }, }); function substitute(arg) { if (arg?.stdout) { return arg.stdout.replace(/\n$/, ''); } return `${arg}`; } class ProcessPromise extends Promise { constructor() { super(...arguments); this._command = ''; this._from = ''; this._resolve = noop; this._reject = noop; this._snapshot = getStore(); this._stdio = ['inherit', 'pipe', 'pipe']; this._nothrow = false; this._quiet = false; this._resolved = false; this._halted = false; this._piped = false; this._prerun = noop; this._postrun = noop; } _bind(cmd, from, resolve, reject, options) { this._command = cmd; this._from = from; this._resolve = resolve; this._reject = reject; this._snapshot = { ...options }; } run() { const $ = this._snapshot; if (this.child) return this; this._prerun(); $.log({ kind: 'cmd', cmd: this._command, verbose: $.verbose && !this._quiet, }); this.child = $.spawn($.prefix + this._command, { cwd: $.cwd ?? $[processCwd], shell: typeof $.shell === 'string' ? $.shell : true, stdio: this._stdio, windowsHide: true, env: $.env, }); this.child.on('close', (code, signal) => { let message = `exit code: ${code}`; if (code != 0 || signal != null) { message = `${stderr || '\n'} at ${this._from}`; message += `\n exit code: ${code}${exitCodeInfo(code) ? ' (' + exitCodeInfo(code) + ')' : ''}`; if (signal != null) { message += `\n signal: ${signal}`; } } let output = new ProcessOutput(code, signal, stdout, stderr, combined, message); if (code === 0 || this._nothrow) { this._resolve(output); } else { this._reject(output); } this._resolved = true; }); this.child.on('error', (err) => { const message = `${err.message}\n` + ` errno: ${err.errno} (${errnoMessage(err.errno)})\n` + ` code: ${err.code}\n` + ` at ${this._from}`; this._reject(new ProcessOutput(null, null, stdout, stderr, combined, message)); this._resolved = true; }); let stdout = '', stderr = '', combined = ''; let onStdout = (data) => { $.log({ kind: 'stdout', data, verbose: $.verbose && !this._quiet }); stdout += data; combined += data; }; let onStderr = (data) => { $.log({ kind: 'stderr', data, verbose: $.verbose && !this._quiet }); stderr += data; combined += data; }; if (!this._piped) this.child.stdout?.on('data', onStdout); this.child.stderr?.on('data', onStderr); this._postrun(); if (this._timeout && this._timeoutSignal) { const t = setTimeout(() => this.kill(this._timeoutSignal), this._timeout); this.finally(() => clearTimeout(t)).catch(noop); } return this; } get stdin() { this.stdio('pipe'); this.run(); assert(this.child); if (this.child.stdin == null) throw new Error('The stdin of subprocess is null.'); return this.child.stdin; } get stdout() { this.run(); assert(this.child); if (this.child.stdout == null) throw new Error('The stdout of subprocess is null.'); return this.child.stdout; } get stderr() { this.run(); assert(this.child); if (this.child.stderr == null) throw new Error('The stderr of subprocess is null.'); return this.child.stderr; } get exitCode() { return this.then((p) => p.exitCode, (p) => p.exitCode); } then(onfulfilled, onrejected) { if (this.isHalted && !this.child) { throw new Error('The process is halted!'); } return super.then(onfulfilled, onrejected); } catch(onrejected) { return super.catch(onrejected); } pipe(dest) { if (typeof dest == 'string') throw new Error('The pipe() method does not take strings. Forgot $?'); if (this._resolved) { if (dest instanceof ProcessPromise) dest.stdin.end(); throw new Error("The pipe() method shouldn't be called after promise is already resolved!"); } this._piped = true; if (dest instanceof ProcessPromise) { dest.stdio('pipe'); dest._prerun = this.run.bind(this); dest._postrun = () => { if (!dest.child) throw new Error('Access to stdin of pipe destination without creation a subprocess.'); this.stdout.pipe(dest.stdin); }; return dest; } else { this._postrun = () => this.stdout.pipe(dest); return this; } } async kill(signal = 'SIGTERM') { if (!this.child) throw new Error('Trying to kill a process without creating one.'); if (!this.child.pid) throw new Error('The process pid is undefined.'); let children = await psTree(this.child.pid); for (const p of children) { try { process.kill(+p.PID, signal); } catch (e) { } } try { process.kill(this.child.pid, signal); } catch (e) { } } stdio(stdin, stdout = 'pipe', stderr = 'pipe') { this._stdio = [stdin, stdout, stderr]; return this; } nothrow() { this._nothrow = true; return this; } quiet() { this._quiet = true; return this; } timeout(d, signal = 'SIGTERM') { this._timeout = parseDuration(d); this._timeoutSignal = signal; return this; } halt() { this._halted = true; return this; } get isHalted() { return this._halted; } } class ProcessOutput extends Error { constructor(code, signal, stdout, stderr, combined, message) { super(message); this._code = code; this._signal = signal; this._stdout = stdout; this._stderr = stderr; this._combined = combined; } toString() { return this._combined; } get stdout() { return this._stdout; } get stderr() { return this._stderr; } get exitCode() { return this._code; } get signal() { return this._signal; } [node_util.inspect.custom]() { let stringify = (s, c) => s.length === 0 ? "''" : c(node_util.inspect(s)); return `ProcessOutput { stdout: ${stringify(this.stdout, chalk.green)}, stderr: ${stringify(this.stderr, chalk.red)}, signal: ${node_util.inspect(this.signal)}, exitCode: ${(this.exitCode === 0 ? chalk.green : chalk.red)(this.exitCode)}${exitCodeInfo(this.exitCode) ? chalk.grey(' (' + exitCodeInfo(this.exitCode) + ')') : ''} }`; } } function syncCwd() { if ($[processCwd] != process.cwd()) process.chdir($[processCwd]); } function cd(dir) { $.log({ kind: 'cd', dir }); process.chdir(dir); $[processCwd] = process.cwd(); } function log(entry) { switch (entry.kind) { case 'cmd': if (!entry.verbose) return; process.stderr.write(formatCmd(entry.cmd)); break; case 'stdout': case 'stderr': if (!entry.verbose) return; process.stderr.write(entry.data); break; case 'cd': if (!$.verbose) return; process.stderr.write('$ ' + chalk.greenBright('cd') + ` ${entry.dir}\n`); break; case 'fetch': if (!$.verbose) return; const init = entry.init ? ' ' + node_util.inspect(entry.init) : ''; process.stderr.write('$ ' + chalk.greenBright('fetch') + ` ${entry.url}${init}\n`); break; case 'retry': if (!$.verbose) return; process.stderr.write(entry.error + '\n'); } } function slash(path) { const isExtendedLengthPath = /^\\\\\?\\/.test(path); const hasNonAscii = /[^\u0000-\u0080]+/.test(path); if (isExtendedLengthPath || hasNonAscii) { return path; } return path.replace(/\\/g, '/'); } const toPath = urlOrPath => urlOrPath instanceof URL ? node_url.fileURLToPath(urlOrPath) : urlOrPath; class FilterStream extends Stream.Transform { constructor(filter) { super({ objectMode: true, transform(data, encoding, callback) { callback(undefined, filter(data) ? data : undefined); }, }); } } const isNegativePattern = pattern => pattern[0] === '!'; const ignoreFilesGlobOptions = { ignore: [ '**/node_modules', '**/flow-typed', '**/coverage', '**/.git', ], absolute: true, dot: true, }; const GITIGNORE_FILES_PATTERN = '**/.gitignore'; const applyBaseToPattern = (pattern, base) => isNegativePattern(pattern) ? '!' + path.posix.join(base, pattern.slice(1)) : path.posix.join(base, pattern); const parseIgnoreFile = (file, cwd) => { const base = slash(path.relative(cwd, path.dirname(file.filePath))); return file.content .split(/\r?\n/) .filter(line => line && !line.startsWith('#')) .map(pattern => applyBaseToPattern(pattern, base)); }; const toRelativePath = (fileOrDirectory, cwd) => { cwd = slash(cwd); if (path.isAbsolute(fileOrDirectory)) { if (slash(fileOrDirectory).startsWith(cwd)) { return path.relative(cwd, fileOrDirectory); } throw new Error(`Path ${fileOrDirectory} is not in cwd ${cwd}`); } return fileOrDirectory; }; const getIsIgnoredPredicate = (files, cwd) => { const patterns = files.flatMap(file => parseIgnoreFile(file, cwd)); const ignores = gitIgnore().add(patterns); return fileOrDirectory => { fileOrDirectory = toPath(fileOrDirectory); fileOrDirectory = toRelativePath(fileOrDirectory, cwd); return fileOrDirectory ? ignores.ignores(slash(fileOrDirectory)) : false; }; }; const normalizeOptions$1 = (options = {}) => ({ cwd: toPath(options.cwd) || process$1.cwd(), }); const isIgnoredByIgnoreFiles = async (patterns, options) => { const {cwd} = normalizeOptions$1(options); const paths = await fastGlob(patterns, {cwd, ...ignoreFilesGlobOptions}); const files = await Promise.all( paths.map(async filePath => ({ filePath, content: await fs.promises.readFile(filePath, 'utf8'), })), ); return getIsIgnoredPredicate(files, cwd); }; const isIgnoredByIgnoreFilesSync = (patterns, options) => { const {cwd} = normalizeOptions$1(options); const paths = fastGlob.sync(patterns, {cwd, ...ignoreFilesGlobOptions}); const files = paths.map(filePath => ({ filePath, content: fs.readFileSync(filePath, 'utf8'), })); return getIsIgnoredPredicate(files, cwd); }; const isGitIgnored = options => isIgnoredByIgnoreFiles(GITIGNORE_FILES_PATTERN, options); const isGitIgnoredSync = options => isIgnoredByIgnoreFilesSync(GITIGNORE_FILES_PATTERN, options); const assertPatternsInput = patterns => { if (patterns.some(pattern => typeof pattern !== 'string')) { throw new TypeError('Patterns must be a string or an array of strings'); } }; const toPatternsArray = patterns => { patterns = [...new Set([patterns].flat())]; assertPatternsInput(patterns); return patterns; }; const checkCwdOption = options => { if (!options.cwd) { return; } let stat; try { stat = fs.statSync(options.cwd); } catch { return; } if (!stat.isDirectory()) { throw new Error('The `cwd` option must be a path to a directory'); } }; const normalizeOptions = (options = {}) => { options = { ignore: [], expandDirectories: true, ...options, cwd: toPath(options.cwd), }; checkCwdOption(options); return options; }; const normalizeArguments = fn => async (patterns, options) => fn(toPatternsArray(patterns), normalizeOptions(options)); const normalizeArgumentsSync = fn => (patterns, options) => fn(toPatternsArray(patterns), normalizeOptions(options)); const getIgnoreFilesPatterns = options => { const {ignoreFiles, gitignore} = options; const patterns = ignoreFiles ? toPatternsArray(ignoreFiles) : []; if (gitignore) { patterns.push(GITIGNORE_FILES_PATTERN); } return patterns; }; const getFilter = async options => { const ignoreFilesPatterns = getIgnoreFilesPatterns(options); return createFilterFunction( ignoreFilesPatterns.length > 0 && await isIgnoredByIgnoreFiles(ignoreFilesPatterns, {cwd: options.cwd}), ); }; const getFilterSync = options => { const ignoreFilesPatterns = getIgnoreFilesPatterns(options); return createFilterFunction( ignoreFilesPatterns.length > 0 && isIgnoredByIgnoreFilesSync(ignoreFilesPatterns, {cwd: options.cwd}), ); }; const createFilterFunction = isIgnored => { const seen = new Set(); return fastGlobResult => { const path$1 = fastGlobResult.path || fastGlobResult; const pathKey = path.normalize(path$1); const seenOrIgnored = seen.has(pathKey) || (isIgnored && isIgnored(path$1)); seen.add(pathKey); return !seenOrIgnored; }; }; const unionFastGlobResults = (results, filter) => results.flat().filter(fastGlobResult => filter(fastGlobResult)); const unionFastGlobStreams = (streams, filter) => merge2(streams).pipe(new FilterStream(fastGlobResult => filter(fastGlobResult))); const convertNegativePatterns = (patterns, options) => { const tasks = []; while (patterns.length > 0) { const index = patterns.findIndex(pattern => isNegativePattern(pattern)); if (index === -1) { tasks.push({patterns, options}); break; } const ignorePattern = patterns[index].slice(1); for (const task of tasks) { task.options.ignore.push(ignorePattern); } if (index !== 0) { tasks.push({ patterns: patterns.slice(0, index), options: { ...options, ignore: [ ...options.ignore, ignorePattern, ], }, }); } patterns = patterns.slice(index + 1); } return tasks; }; const getDirGlobOptions = (options, cwd) => ({ ...(cwd ? {cwd} : {}), ...(Array.isArray(options) ? {files: options} : options), }); const generateTasks = async (patterns, options) => { const globTasks = convertNegativePatterns(patterns, options); const {cwd, expandDirectories} = options; if (!expandDirectories) { return globTasks; } const patternExpandOptions = getDirGlobOptions(expandDirectories, cwd); const ignoreExpandOptions = cwd ? {cwd} : undefined; return Promise.all( globTasks.map(async task => { let {patterns, options} = task; [ patterns, options.ignore, ] = await Promise.all([ dirGlob(patterns, patternExpandOptions), dirGlob(options.ignore, ignoreExpandOptions), ]); return {patterns, options}; }), ); }; const generateTasksSync = (patterns, options) => { const globTasks = convertNegativePatterns(patterns, options); const {cwd, expandDirectories} = options; if (!expandDirectories) { return globTasks; } const patternExpandOptions = getDirGlobOptions(expandDirectories, cwd); const ignoreExpandOptions = cwd ? {cwd} : undefined; return globTasks.map(task => { let {patterns, options} = task; patterns = dirGlob.sync(patterns, patternExpandOptions); options.ignore = dirGlob.sync(options.ignore, ignoreExpandOptions); return {patterns, options}; }); }; const globby = normalizeArguments(async (patterns, options) => { const [ tasks, filter, ] = await Promise.all([ generateTasks(patterns, options), getFilter(options), ]); const results = await Promise.all(tasks.map(task => fastGlob(task.patterns, task.options))); return unionFastGlobResults(results, filter); }); const globbySync = normalizeArgumentsSync((patterns, options) => { const tasks = generateTasksSync(patterns, options); const filter = getFilterSync(options); const results = tasks.map(task => fastGlob.sync(task.patterns, task.options)); return unionFastGlobResults(results, filter); }); const globbyStream = normalizeArgumentsSync((patterns, options) => { const tasks = generateTasksSync(patterns, options); const filter = getFilterSync(options); const streams = tasks.map(task => fastGlob.stream(task.patterns, task.options)); return unionFastGlobStreams(streams, filter); }); const isDynamicPattern = normalizeArgumentsSync( (patterns, options) => patterns.some(pattern => fastGlob.isDynamicPattern(pattern, options)), ); const generateGlobTasks = normalizeArguments(generateTasks); const generateGlobTasksSync = normalizeArgumentsSync(generateTasksSync); var globbyModule = /*#__PURE__*/Object.freeze({ __proto__: null, generateGlobTasks: generateGlobTasks, generateGlobTasksSync: generateGlobTasksSync, globby: globby, globbyStream: globbyStream, globbySync: globbySync, isDynamicPattern: isDynamicPattern, isGitIgnored: isGitIgnored, isGitIgnoredSync: isGitIgnoredSync }); minimist(process.argv.slice(2)); Object.assign(function globby$1(patterns, options) { return globby(patterns, options); }, globbyModule); var name$1 = "dns-setting"; var version = "1.0.__tick__"; var install = "npm i -g dns-setting"; var type = "module"; var description = "dns management: query, modify, shield corresponding domain name resolution"; var main$1 = "index.js"; var scripts = { test: "echo \"Error: no test specified\" && exit 1", serialize: "serialize=true node db.js", start: "node index.js", build: "rollup --config rollup.config.js" }; var bin = { ds: "./cli.js" }; var dependencies = { express: "^4.18.2", "native-dns": "^0.7.0", sqlite3: "^5.1.4", zx: "^7.2.0" }; var keywords = [ "dns", "management", "local", "dev", "serve", "config" ]; var author = ""; var license = "MIT"; var devDependencies = { "@robmarr/rollup-plugin-shebang": "^1.0.1", "@rollup/plugin-commonjs": "^24.0.1", "@rollup/plugin-json": "^6.0.0", "@rollup/plugin-node-resolve": "^15.0.1", "@rollup/plugin-terser": "^0.4.0", rollup: "^3.19.1", "rollup-plugin-cleanup": "^3.2.1", "rollup-plugin-copy": "^3.4.0", "rollup-plugin-delete": "^2.0.0", "rollup-plugin-folder-input": "^1.0.1" }; var pack = { name: name$1, version: version, install: install, type: type, description: description, main: main$1, scripts: scripts, bin: bin, dependencies: dependencies, keywords: keywords, author: author, license: license, devDependencies: devDependencies }; let { name } = pack; let argv = process.argv; console.log("argv", argv); async function main(argv) { let str = (await $`npm list -g ${name} --depth 0`).stdout; str = str?.split("\n")[0] + "/node_modules/" + name; cd(str); $`pwd && ls`; if (argv[2] == "init") { $`serialize=true node db.js`; } if (argv[2] == "start") { $`node index.js`; } if (!argv[2]) { console.log("`sudo ds init` or `sudo ds start`"); } } main(argv);