diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..cef0944 --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,9 @@ +To run frontend, please + +1. rm -rf node_modules +2. do `npm install` +3. do `npm run dev` + +and visit http://localhost:5173 + +Thanks. diff --git a/frontend/node_modules/.bin/browserslist b/frontend/node_modules/.bin/browserslist deleted file mode 100755 index 78c08d7..0000000 --- a/frontend/node_modules/.bin/browserslist +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env node - -var fs = require('fs') -var updateDb = require('update-browserslist-db') - -var browserslist = require('./') -var pkg = require('./package.json') - -var args = process.argv.slice(2) - -var USAGE = - 'Usage:\n' + - ' npx browserslist\n' + - ' npx browserslist "QUERIES"\n' + - ' npx browserslist --json "QUERIES"\n' + - ' npx browserslist --config="path/to/browserlist/file"\n' + - ' npx browserslist --coverage "QUERIES"\n' + - ' npx browserslist --coverage=US "QUERIES"\n' + - ' npx browserslist --coverage=US,RU,global "QUERIES"\n' + - ' npx browserslist --env="environment name defined in config"\n' + - ' npx browserslist --stats="path/to/browserlist/stats/file"\n' + - ' npx browserslist --mobile-to-desktop\n' + - ' npx browserslist --ignore-unknown-versions\n' - -function isArg(arg) { - return args.some(function (str) { - return str === arg || str.indexOf(arg + '=') === 0 - }) -} - -function error(msg) { - process.stderr.write('browserslist: ' + msg + '\n') - process.exit(1) -} - -if (isArg('--help') || isArg('-h')) { - process.stdout.write(pkg.description + '.\n\n' + USAGE + '\n') -} else if (isArg('--version') || isArg('-v')) { - process.stdout.write('browserslist ' + pkg.version + '\n') -} else if (isArg('--update-db')) { - /* c8 ignore next 8 */ - process.stdout.write( - 'The --update-db command is deprecated.\n' + - 'Please use npx update-browserslist-db@latest instead.\n' - ) - process.stdout.write('Browserslist DB update will still be made.\n') - updateDb(function (str) { - process.stdout.write(str) - }) -} else { - var mode = 'browsers' - var opts = {} - var queries - var areas - - for (var i = 0; i < args.length; i++) { - if (args[i][0] !== '-') { - queries = args[i].replace(/^["']|["']$/g, '') - continue - } - - var arg = args[i].split('=') - var name = arg[0] - var value = arg[1] - - if (value) value = value.replace(/^["']|["']$/g, '') - - if (name === '--config' || name === '-b') { - opts.config = value - } else if (name === '--env' || name === '-e') { - opts.env = value - } else if (name === '--stats' || name === '-s') { - opts.stats = value - } else if (name === '--coverage' || name === '-c') { - if (mode !== 'json') mode = 'coverage' - if (value) { - areas = value.split(',') - } else { - areas = ['global'] - } - } else if (name === '--json') { - mode = 'json' - } else if (name === '--mobile-to-desktop') { - /* c8 ignore next */ - opts.mobileToDesktop = true - } else if (name === '--ignore-unknown-versions') { - /* c8 ignore next */ - opts.ignoreUnknownVersions = true - } else { - error('Unknown arguments ' + args[i] + '.\n\n' + USAGE) - } - } - - var browsers - try { - browsers = browserslist(queries, opts) - } catch (e) { - if (e.name === 'BrowserslistError') { - error(e.message) - } /* c8 ignore start */ else { - throw e - } /* c8 ignore end */ - } - - var coverage - if (mode === 'browsers') { - browsers.forEach(function (browser) { - process.stdout.write(browser + '\n') - }) - } else if (areas) { - coverage = areas.map(function (area) { - var stats - if (area !== 'global') { - stats = area - } else if (opts.stats) { - stats = JSON.parse(fs.readFileSync(opts.stats)) - } - var result = browserslist.coverage(browsers, stats) - var round = Math.round(result * 100) / 100.0 - - return [area, round] - }) - - if (mode === 'coverage') { - var prefix = 'These browsers account for ' - process.stdout.write(prefix) - coverage.forEach(function (data, index) { - var area = data[0] - var round = data[1] - var end = 'globally' - if (area && area !== 'global') { - end = 'in the ' + area.toUpperCase() - } else if (opts.stats) { - end = 'in custom statistics' - } - - if (index !== 0) { - process.stdout.write(prefix.replace(/./g, ' ')) - } - - process.stdout.write(round + '% of all users ' + end + '\n') - }) - } - } - - if (mode === 'json') { - var data = { browsers: browsers } - if (coverage) { - data.coverage = coverage.reduce(function (object, j) { - object[j[0]] = j[1] - return object - }, {}) - } - process.stdout.write(JSON.stringify(data, null, ' ') + '\n') - } -} diff --git a/frontend/node_modules/.bin/browserslist b/frontend/node_modules/.bin/browserslist new file mode 120000 index 0000000..3cd991b --- /dev/null +++ b/frontend/node_modules/.bin/browserslist @@ -0,0 +1 @@ +../browserslist/cli.js \ No newline at end of file diff --git a/frontend/node_modules/.bin/esbuild b/frontend/node_modules/.bin/esbuild deleted file mode 100755 index 845aa89..0000000 Binary files a/frontend/node_modules/.bin/esbuild and /dev/null differ diff --git a/frontend/node_modules/.bin/esbuild b/frontend/node_modules/.bin/esbuild new file mode 120000 index 0000000..c83ac07 --- /dev/null +++ b/frontend/node_modules/.bin/esbuild @@ -0,0 +1 @@ +../esbuild/bin/esbuild \ No newline at end of file diff --git a/frontend/node_modules/.bin/jsesc b/frontend/node_modules/.bin/jsesc deleted file mode 100755 index e9a541d..0000000 --- a/frontend/node_modules/.bin/jsesc +++ /dev/null @@ -1,148 +0,0 @@ -#!/usr/bin/env node -(function() { - - var fs = require('fs'); - var stringEscape = require('../jsesc.js'); - var strings = process.argv.splice(2); - var stdin = process.stdin; - var data; - var timeout; - var isObject = false; - var options = {}; - var log = console.log; - - var main = function() { - var option = strings[0]; - - if (/^(?:-h|--help|undefined)$/.test(option)) { - log( - 'jsesc v%s - https://mths.be/jsesc', - stringEscape.version - ); - log([ - '\nUsage:\n', - '\tjsesc [string]', - '\tjsesc [-s | --single-quotes] [string]', - '\tjsesc [-d | --double-quotes] [string]', - '\tjsesc [-w | --wrap] [string]', - '\tjsesc [-e | --escape-everything] [string]', - '\tjsesc [-t | --escape-etago] [string]', - '\tjsesc [-6 | --es6] [string]', - '\tjsesc [-l | --lowercase-hex] [string]', - '\tjsesc [-j | --json] [string]', - '\tjsesc [-o | --object] [stringified_object]', // `JSON.parse()` the argument - '\tjsesc [-p | --pretty] [string]', // `compact: false` - '\tjsesc [-v | --version]', - '\tjsesc [-h | --help]', - '\nExamples:\n', - '\tjsesc \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', - '\tjsesc --json \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', - '\tjsesc --json --escape-everything \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', - '\tjsesc --double-quotes --wrap \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', - '\techo \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\' | jsesc' - ].join('\n')); - return process.exit(1); - } - - if (/^(?:-v|--version)$/.test(option)) { - log('v%s', stringEscape.version); - return process.exit(1); - } - - strings.forEach(function(string) { - // Process options - if (/^(?:-s|--single-quotes)$/.test(string)) { - options.quotes = 'single'; - return; - } - if (/^(?:-d|--double-quotes)$/.test(string)) { - options.quotes = 'double'; - return; - } - if (/^(?:-w|--wrap)$/.test(string)) { - options.wrap = true; - return; - } - if (/^(?:-e|--escape-everything)$/.test(string)) { - options.escapeEverything = true; - return; - } - if (/^(?:-t|--escape-etago)$/.test(string)) { - options.escapeEtago = true; - return; - } - if (/^(?:-6|--es6)$/.test(string)) { - options.es6 = true; - return; - } - if (/^(?:-l|--lowercase-hex)$/.test(string)) { - options.lowercaseHex = true; - return; - } - if (/^(?:-j|--json)$/.test(string)) { - options.json = true; - return; - } - if (/^(?:-o|--object)$/.test(string)) { - isObject = true; - return; - } - if (/^(?:-p|--pretty)$/.test(string)) { - isObject = true; - options.compact = false; - return; - } - - // Process string(s) - var result; - try { - if (isObject) { - string = JSON.parse(string); - } - result = stringEscape(string, options); - log(result); - } catch(error) { - log(error.message + '\n'); - log('Error: failed to escape.'); - log('If you think this is a bug in jsesc, please report it:'); - log('https://github.com/mathiasbynens/jsesc/issues/new'); - log( - '\nStack trace using jsesc@%s:\n', - stringEscape.version - ); - log(error.stack); - return process.exit(1); - } - }); - // Return with exit status 0 outside of the `forEach` loop, in case - // multiple strings were passed in. - return process.exit(0); - - }; - - if (stdin.isTTY) { - // handle shell arguments - main(); - } else { - // Either the script is called from within a non-TTY context, - // or `stdin` content is being piped in. - if (!process.stdout.isTTY) { // called from a non-TTY context - timeout = setTimeout(function() { - // if no piped data arrived after a while, handle shell arguments - main(); - }, 250); - } - - data = ''; - stdin.on('data', function(chunk) { - clearTimeout(timeout); - data += chunk; - }); - stdin.on('end', function() { - strings.push(data.trim()); - main(); - }); - stdin.resume(); - } - -}()); diff --git a/frontend/node_modules/.bin/jsesc b/frontend/node_modules/.bin/jsesc new file mode 120000 index 0000000..7237604 --- /dev/null +++ b/frontend/node_modules/.bin/jsesc @@ -0,0 +1 @@ +../jsesc/bin/jsesc \ No newline at end of file diff --git a/frontend/node_modules/.bin/json5 b/frontend/node_modules/.bin/json5 deleted file mode 100755 index 93cb809..0000000 --- a/frontend/node_modules/.bin/json5 +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env node - -const fs = require('fs') -const path = require('path') -const pkg = require('../package.json') -const JSON5 = require('./') - -const argv = parseArgs() - -if (argv.version) { - version() -} else if (argv.help) { - usage() -} else { - const inFilename = argv.defaults[0] - - let readStream - if (inFilename) { - readStream = fs.createReadStream(inFilename) - } else { - readStream = process.stdin - } - - let json5 = '' - readStream.on('data', data => { - json5 += data - }) - - readStream.on('end', () => { - let space - if (argv.space === 't' || argv.space === 'tab') { - space = '\t' - } else { - space = Number(argv.space) - } - - let value - try { - value = JSON5.parse(json5) - if (!argv.validate) { - const json = JSON.stringify(value, null, space) - - let writeStream - - // --convert is for backward compatibility with v0.5.1. If - // specified with and not --out-file, then a file with - // the same name but with a .json extension will be written. - if (argv.convert && inFilename && !argv.outFile) { - const parsedFilename = path.parse(inFilename) - const outFilename = path.format( - Object.assign( - parsedFilename, - {base: path.basename(parsedFilename.base, parsedFilename.ext) + '.json'} - ) - ) - - writeStream = fs.createWriteStream(outFilename) - } else if (argv.outFile) { - writeStream = fs.createWriteStream(argv.outFile) - } else { - writeStream = process.stdout - } - - writeStream.write(json) - } - } catch (err) { - console.error(err.message) - process.exit(1) - } - }) -} - -function parseArgs () { - let convert - let space - let validate - let outFile - let version - let help - const defaults = [] - - const args = process.argv.slice(2) - for (let i = 0; i < args.length; i++) { - const arg = args[i] - switch (arg) { - case '--convert': - case '-c': - convert = true - break - - case '--space': - case '-s': - space = args[++i] - break - - case '--validate': - case '-v': - validate = true - break - - case '--out-file': - case '-o': - outFile = args[++i] - break - - case '--version': - case '-V': - version = true - break - - case '--help': - case '-h': - help = true - break - - default: - defaults.push(arg) - break - } - } - - return { - convert, - space, - validate, - outFile, - version, - help, - defaults, - } -} - -function version () { - console.log(pkg.version) -} - -function usage () { - console.log( - ` - Usage: json5 [options] - - If is not provided, then STDIN is used. - - Options: - - -s, --space The number of spaces to indent or 't' for tabs - -o, --out-file [file] Output to the specified file, otherwise STDOUT - -v, --validate Validate JSON5 but do not output JSON - -V, --version Output the version number - -h, --help Output usage information` - ) -} diff --git a/frontend/node_modules/.bin/json5 b/frontend/node_modules/.bin/json5 new file mode 120000 index 0000000..217f379 --- /dev/null +++ b/frontend/node_modules/.bin/json5 @@ -0,0 +1 @@ +../json5/lib/cli.js \ No newline at end of file diff --git a/frontend/node_modules/.bin/loose-envify b/frontend/node_modules/.bin/loose-envify deleted file mode 100755 index c0b63cb..0000000 --- a/frontend/node_modules/.bin/loose-envify +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env node -'use strict'; - -var looseEnvify = require('./'); -var fs = require('fs'); - -if (process.argv[2]) { - fs.createReadStream(process.argv[2], {encoding: 'utf8'}) - .pipe(looseEnvify(process.argv[2])) - .pipe(process.stdout); -} else { - process.stdin.resume() - process.stdin - .pipe(looseEnvify(__filename)) - .pipe(process.stdout); -} diff --git a/frontend/node_modules/.bin/loose-envify b/frontend/node_modules/.bin/loose-envify new file mode 120000 index 0000000..ed9009c --- /dev/null +++ b/frontend/node_modules/.bin/loose-envify @@ -0,0 +1 @@ +../loose-envify/cli.js \ No newline at end of file diff --git a/frontend/node_modules/.bin/nanoid b/frontend/node_modules/.bin/nanoid deleted file mode 100755 index c76db0f..0000000 --- a/frontend/node_modules/.bin/nanoid +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env node - -let { nanoid, customAlphabet } = require('..') - -function print(msg) { - process.stdout.write(msg + '\n') -} - -function error(msg) { - process.stderr.write(msg + '\n') - process.exit(1) -} - -if (process.argv.includes('--help') || process.argv.includes('-h')) { - print(` - Usage - $ nanoid [options] - - Options - -s, --size Generated ID size - -a, --alphabet Alphabet to use - -h, --help Show this help - - Examples - $ nanoid --s 15 - S9sBF77U6sDB8Yg - - $ nanoid --size 10 --alphabet abc - bcabababca`) - process.exit() -} - -let alphabet, size -for (let i = 2; i < process.argv.length; i++) { - let arg = process.argv[i] - if (arg === '--size' || arg === '-s') { - size = Number(process.argv[i + 1]) - i += 1 - if (Number.isNaN(size) || size <= 0) { - error('Size must be positive integer') - } - } else if (arg === '--alphabet' || arg === '-a') { - alphabet = process.argv[i + 1] - i += 1 - } else { - error('Unknown argument ' + arg) - } -} - -if (alphabet) { - let customNanoid = customAlphabet(alphabet, size) - print(customNanoid()) -} else { - print(nanoid(size)) -} diff --git a/frontend/node_modules/.bin/nanoid b/frontend/node_modules/.bin/nanoid new file mode 120000 index 0000000..e2be547 --- /dev/null +++ b/frontend/node_modules/.bin/nanoid @@ -0,0 +1 @@ +../nanoid/bin/nanoid.cjs \ No newline at end of file diff --git a/frontend/node_modules/.bin/parser b/frontend/node_modules/.bin/parser deleted file mode 100755 index 4808c5e..0000000 --- a/frontend/node_modules/.bin/parser +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env node -/* eslint-disable no-var, unicorn/prefer-node-protocol */ - -var parser = require(".."); -var fs = require("fs"); - -var filename = process.argv[2]; -if (!filename) { - console.error("no filename specified"); -} else { - var file = fs.readFileSync(filename, "utf8"); - var ast = parser.parse(file); - - console.log(JSON.stringify(ast, null, " ")); -} diff --git a/frontend/node_modules/.bin/parser b/frontend/node_modules/.bin/parser new file mode 120000 index 0000000..ce7bf97 --- /dev/null +++ b/frontend/node_modules/.bin/parser @@ -0,0 +1 @@ +../@babel/parser/bin/babel-parser.js \ No newline at end of file diff --git a/frontend/node_modules/.bin/rollup b/frontend/node_modules/.bin/rollup deleted file mode 100755 index b6395c2..0000000 --- a/frontend/node_modules/.bin/rollup +++ /dev/null @@ -1,1884 +0,0 @@ -#!/usr/bin/env node -/* - @license - Rollup.js v4.44.1 - Thu, 26 Jun 2025 04:33:05 GMT - commit 5a7f9e215a11de165b85dafd64350474847ec6db - - https://github.com/rollup/rollup - - Released under the MIT License. -*/ -'use strict'; - -Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - -const process$1 = require('node:process'); -const rollup = require('../shared/rollup.js'); -const require$$2 = require('util'); -const require$$0 = require('path'); -const require$$0$1 = require('fs'); -const parseAst_js = require('../shared/parseAst.js'); -const fseventsImporter = require('../shared/fsevents-importer.js'); -const promises = require('node:fs/promises'); -const path = require('node:path'); -const loadConfigFile_js = require('../shared/loadConfigFile.js'); -require('../native.js'); -require('node:perf_hooks'); -require('node:url'); -require('../getLogFilter.js'); - -const help = "rollup version __VERSION__\n=====================================\n\nUsage: rollup [options] \n\nBasic options:\n\n-c, --config Use this config file (if argument is used but value\n is unspecified, defaults to rollup.config.js)\n-d, --dir Directory for chunks (if absent, prints to stdout)\n-e, --external Comma-separate list of module IDs to exclude\n-f, --format Type of output (amd, cjs, es, iife, umd, system)\n-g, --globals Comma-separate list of `moduleID:Global` pairs\n-h, --help Show this help message\n-i, --input Input (alternative to )\n-m, --sourcemap Generate sourcemap (`-m inline` for inline map)\n-n, --name Name for UMD export\n-o, --file Single output file (if absent, prints to stdout)\n-p, --plugin Use the plugin specified (may be repeated)\n-v, --version Show version number\n-w, --watch Watch files in bundle and rebuild on changes\n--amd.autoId Generate the AMD ID based off the chunk name\n--amd.basePath Path to prepend to auto generated AMD ID\n--amd.define Function to use in place of `define`\n--amd.forceJsExtensionForImports Use `.js` extension in AMD imports\n--amd.id ID for AMD module (default is anonymous)\n--assetFileNames Name pattern for emitted assets\n--banner Code to insert at top of bundle (outside wrapper)\n--chunkFileNames Name pattern for emitted secondary chunks\n--compact Minify wrapper code\n--context Specify top-level `this` value\n--no-dynamicImportInCjs Write external dynamic CommonJS imports as require\n--entryFileNames Name pattern for emitted entry chunks\n--environment Settings passed to config file (see example)\n--no-esModule Do not add __esModule property\n--exports Specify export mode (auto, default, named, none)\n--extend Extend global variable defined by --name\n--no-externalImportAttributes Omit import attributes in \"es\" output\n--no-externalLiveBindings Do not generate code to support live bindings\n--failAfterWarnings Exit with an error if the build produced warnings\n--filterLogs Filter log messages\n--footer Code to insert at end of bundle (outside wrapper)\n--forceExit Force exit the process when done\n--no-freeze Do not freeze namespace objects\n--generatedCode Which code features to use (es5/es2015)\n--generatedCode.arrowFunctions Use arrow functions in generated code\n--generatedCode.constBindings Use \"const\" in generated code\n--generatedCode.objectShorthand Use shorthand properties in generated code\n--no-generatedCode.reservedNamesAsProps Always quote reserved names as props\n--generatedCode.symbols Use symbols in generated code\n--hashCharacters Use the specified character set for file hashes\n--no-hoistTransitiveImports Do not hoist transitive imports into entry chunks\n--importAttributesKey Use the specified keyword for import attributes\n--no-indent Don't indent result\n--inlineDynamicImports Create single bundle when using dynamic imports\n--no-interop Do not include interop block\n--intro Code to insert at top of bundle (inside wrapper)\n--logLevel Which kind of logs to display\n--no-makeAbsoluteExternalsRelative Prevent normalization of external imports\n--maxParallelFileOps How many files to read in parallel\n--minifyInternalExports Force or disable minification of internal exports\n--noConflict Generate a noConflict method for UMD globals\n--outro Code to insert at end of bundle (inside wrapper)\n--perf Display performance timings\n--no-preserveEntrySignatures Avoid facade chunks for entry points\n--preserveModules Preserve module structure\n--preserveModulesRoot Put preserved modules under this path at root level\n--preserveSymlinks Do not follow symlinks when resolving files\n--no-reexportProtoFromExternal Ignore `__proto__` in star re-exports\n--no-sanitizeFileName Do not replace invalid characters in file names\n--shimMissingExports Create shim variables for missing exports\n--silent Don't print warnings\n--sourcemapBaseUrl Emit absolute sourcemap URLs with given base\n--sourcemapDebugIds Emit unique debug ids in source and sourcemaps\n--sourcemapExcludeSources Do not include source code in source maps\n--sourcemapFile Specify bundle position for source maps\n--sourcemapFileNames Name pattern for emitted sourcemaps\n--stdin=ext Specify file extension used for stdin input\n--no-stdin Do not read \"-\" from stdin\n--no-strict Don't emit `\"use strict\";` in the generated modules\n--strictDeprecations Throw errors for deprecated features\n--no-systemNullSetters Do not replace empty SystemJS setters with `null`\n--no-treeshake Disable tree-shaking optimisations\n--no-treeshake.annotations Ignore pure call annotations\n--treeshake.correctVarValueBeforeDeclaration Deoptimize variables until declared\n--treeshake.manualPureFunctions Manually declare functions as pure\n--no-treeshake.moduleSideEffects Assume modules have no side effects\n--no-treeshake.propertyReadSideEffects Ignore property access side effects\n--no-treeshake.tryCatchDeoptimization Do not turn off try-catch-tree-shaking\n--no-treeshake.unknownGlobalSideEffects Assume unknown globals do not throw\n--validate Validate output\n--waitForBundleInput Wait for bundle input files\n--watch.allowInputInsideOutputPath Whether the input path is allowed to be a\n subpath of the output path\n--watch.buildDelay Throttle watch rebuilds\n--no-watch.clearScreen Do not clear the screen when rebuilding\n--watch.exclude Exclude files from being watched\n--watch.include Limit watching to specified files\n--watch.onBundleEnd Shell command to run on `\"BUNDLE_END\"` event\n--watch.onBundleStart Shell command to run on `\"BUNDLE_START\"` event\n--watch.onEnd Shell command to run on `\"END\"` event\n--watch.onError Shell command to run on `\"ERROR\"` event\n--watch.onStart Shell command to run on `\"START\"` event\n--watch.skipWrite Do not write files to disk when watching\n\nExamples:\n\n# use settings in config file\nrollup -c\n\n# in config file, process.env.INCLUDE_DEPS === 'true'\n# and process.env.BUILD === 'production'\nrollup -c --environment INCLUDE_DEPS,BUILD:production\n\n# create CommonJS bundle.js from src/main.js\nrollup --format=cjs --file=bundle.js -- src/main.js\n\n# create self-executing IIFE using `window.jQuery`\n# and `window._` as external globals\nrollup -f iife --globals jquery:jQuery,lodash:_ \\\n -i src/app.js -o build/app.js -m build/app.js.map\n\nNotes:\n\n* When piping to stdout, only inline sourcemaps are permitted\n\nFor more information visit https://rollupjs.org\n"; - -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -function camelCase(str) { - // Handle the case where an argument is provided as camel case, e.g., fooBar. - // by ensuring that the string isn't already mixed case: - const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); - if (!isCamelCase) { - str = str.toLowerCase(); - } - if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { - return str; - } - else { - let camelcase = ''; - let nextChrUpper = false; - const leadingHyphens = str.match(/^-+/); - for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { - let chr = str.charAt(i); - if (nextChrUpper) { - nextChrUpper = false; - chr = chr.toUpperCase(); - } - if (i !== 0 && (chr === '-' || chr === '_')) { - nextChrUpper = true; - } - else if (chr !== '-' && chr !== '_') { - camelcase += chr; - } - } - return camelcase; - } -} -function decamelize(str, joinString) { - const lowercase = str.toLowerCase(); - joinString = joinString || '-'; - let notCamelcase = ''; - for (let i = 0; i < str.length; i++) { - const chrLower = lowercase.charAt(i); - const chrString = str.charAt(i); - if (chrLower !== chrString && i > 0) { - notCamelcase += `${joinString}${lowercase.charAt(i)}`; - } - else { - notCamelcase += chrString; - } - } - return notCamelcase; -} -function looksLikeNumber(x) { - if (x === null || x === undefined) - return false; - // if loaded from config, may already be a number. - if (typeof x === 'number') - return true; - // hexadecimal. - if (/^0x[0-9a-f]+$/i.test(x)) - return true; - // don't treat 0123 as a number; as it drops the leading '0'. - if (/^0[^.]/.test(x)) - return false; - return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); -} - -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -// take an un-split argv string and tokenize it. -function tokenizeArgString(argString) { - if (Array.isArray(argString)) { - return argString.map(e => typeof e !== 'string' ? e + '' : e); - } - argString = argString.trim(); - let i = 0; - let prevC = null; - let c = null; - let opening = null; - const args = []; - for (let ii = 0; ii < argString.length; ii++) { - prevC = c; - c = argString.charAt(ii); - // split on spaces unless we're in quotes. - if (c === ' ' && !opening) { - if (!(prevC === ' ')) { - i++; - } - continue; - } - // don't split the string if we're in matching - // opening or closing single and double quotes. - if (c === opening) { - opening = null; - } - else if ((c === "'" || c === '"') && !opening) { - opening = c; - } - if (!args[i]) - args[i] = ''; - args[i] += c; - } - return args; -} - -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -var DefaultValuesForTypeKey; -(function (DefaultValuesForTypeKey) { - DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; - DefaultValuesForTypeKey["STRING"] = "string"; - DefaultValuesForTypeKey["NUMBER"] = "number"; - DefaultValuesForTypeKey["ARRAY"] = "array"; -})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); - -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -let mixin; -class YargsParser { - constructor(_mixin) { - mixin = _mixin; - } - parse(argsInput, options) { - const opts = Object.assign({ - alias: undefined, - array: undefined, - boolean: undefined, - config: undefined, - configObjects: undefined, - configuration: undefined, - coerce: undefined, - count: undefined, - default: undefined, - envPrefix: undefined, - narg: undefined, - normalize: undefined, - string: undefined, - number: undefined, - __: undefined, - key: undefined - }, options); - // allow a string argument to be passed in rather - // than an argv array. - const args = tokenizeArgString(argsInput); - // tokenizeArgString adds extra quotes to args if argsInput is a string - // only strip those extra quotes in processValue if argsInput is a string - const inputIsString = typeof argsInput === 'string'; - // aliases might have transitive relationships, normalize this. - const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); - const configuration = Object.assign({ - 'boolean-negation': true, - 'camel-case-expansion': true, - 'combine-arrays': false, - 'dot-notation': true, - 'duplicate-arguments-array': true, - 'flatten-duplicate-arrays': true, - 'greedy-arrays': true, - 'halt-at-non-option': false, - 'nargs-eats-options': false, - 'negation-prefix': 'no-', - 'parse-numbers': true, - 'parse-positional-numbers': true, - 'populate--': false, - 'set-placeholder-key': false, - 'short-option-groups': true, - 'strip-aliased': false, - 'strip-dashed': false, - 'unknown-options-as-args': false - }, opts.configuration); - const defaults = Object.assign(Object.create(null), opts.default); - const configObjects = opts.configObjects || []; - const envPrefix = opts.envPrefix; - const notFlagsOption = configuration['populate--']; - const notFlagsArgv = notFlagsOption ? '--' : '_'; - const newAliases = Object.create(null); - const defaulted = Object.create(null); - // allow a i18n handler to be passed in, default to a fake one (util.format). - const __ = opts.__ || mixin.format; - const flags = { - aliases: Object.create(null), - arrays: Object.create(null), - bools: Object.create(null), - strings: Object.create(null), - numbers: Object.create(null), - counts: Object.create(null), - normalize: Object.create(null), - configs: Object.create(null), - nargs: Object.create(null), - coercions: Object.create(null), - keys: [] - }; - const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; - const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); - [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { - const key = typeof opt === 'object' ? opt.key : opt; - // assign to flags[bools|strings|numbers] - const assignment = Object.keys(opt).map(function (key) { - const arrayFlagKeys = { - boolean: 'bools', - string: 'strings', - number: 'numbers' - }; - return arrayFlagKeys[key]; - }).filter(Boolean).pop(); - // assign key to be coerced - if (assignment) { - flags[assignment][key] = true; - } - flags.arrays[key] = true; - flags.keys.push(key); - }); - [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { - flags.bools[key] = true; - flags.keys.push(key); - }); - [].concat(opts.string || []).filter(Boolean).forEach(function (key) { - flags.strings[key] = true; - flags.keys.push(key); - }); - [].concat(opts.number || []).filter(Boolean).forEach(function (key) { - flags.numbers[key] = true; - flags.keys.push(key); - }); - [].concat(opts.count || []).filter(Boolean).forEach(function (key) { - flags.counts[key] = true; - flags.keys.push(key); - }); - [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { - flags.normalize[key] = true; - flags.keys.push(key); - }); - if (typeof opts.narg === 'object') { - Object.entries(opts.narg).forEach(([key, value]) => { - if (typeof value === 'number') { - flags.nargs[key] = value; - flags.keys.push(key); - } - }); - } - if (typeof opts.coerce === 'object') { - Object.entries(opts.coerce).forEach(([key, value]) => { - if (typeof value === 'function') { - flags.coercions[key] = value; - flags.keys.push(key); - } - }); - } - if (typeof opts.config !== 'undefined') { - if (Array.isArray(opts.config) || typeof opts.config === 'string') { - [].concat(opts.config).filter(Boolean).forEach(function (key) { - flags.configs[key] = true; - }); - } - else if (typeof opts.config === 'object') { - Object.entries(opts.config).forEach(([key, value]) => { - if (typeof value === 'boolean' || typeof value === 'function') { - flags.configs[key] = value; - } - }); - } - } - // create a lookup table that takes into account all - // combinations of aliases: {f: ['foo'], foo: ['f']} - extendAliases(opts.key, aliases, opts.default, flags.arrays); - // apply default values to all aliases. - Object.keys(defaults).forEach(function (key) { - (flags.aliases[key] || []).forEach(function (alias) { - defaults[alias] = defaults[key]; - }); - }); - let error = null; - checkConfiguration(); - let notFlags = []; - const argv = Object.assign(Object.create(null), { _: [] }); - // TODO(bcoe): for the first pass at removing object prototype we didn't - // remove all prototypes from objects returned by this API, we might want - // to gradually move towards doing so. - const argvReturn = {}; - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - const truncatedArg = arg.replace(/^-{3,}/, '---'); - let broken; - let key; - let letters; - let m; - let next; - let value; - // any unknown option (except for end-of-options, "--") - if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { - pushPositional(arg); - // ---, ---=, ----, etc, - } - else if (truncatedArg.match(/^---+(=|$)/)) { - // options without key name are invalid. - pushPositional(arg); - continue; - // -- separated by = - } - else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { - // Using [\s\S] instead of . because js doesn't support the - // 'dotall' regex modifier. See: - // http://stackoverflow.com/a/1068308/13216 - m = arg.match(/^--?([^=]+)=([\s\S]*)$/); - // arrays format = '--f=a b c' - if (m !== null && Array.isArray(m) && m.length >= 3) { - if (checkAllAliases(m[1], flags.arrays)) { - i = eatArray(i, m[1], args, m[2]); - } - else if (checkAllAliases(m[1], flags.nargs) !== false) { - // nargs format = '--f=monkey washing cat' - i = eatNargs(i, m[1], args, m[2]); - } - else { - setArg(m[1], m[2], true); - } - } - } - else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { - m = arg.match(negatedBoolean); - if (m !== null && Array.isArray(m) && m.length >= 2) { - key = m[1]; - setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); - } - // -- separated by space. - } - else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { - m = arg.match(/^--?(.+)/); - if (m !== null && Array.isArray(m) && m.length >= 2) { - key = m[1]; - if (checkAllAliases(key, flags.arrays)) { - // array format = '--foo a b c' - i = eatArray(i, key, args); - } - else if (checkAllAliases(key, flags.nargs) !== false) { - // nargs format = '--foo a b c' - // should be truthy even if: flags.nargs[key] === 0 - i = eatNargs(i, key, args); - } - else { - next = args[i + 1]; - if (next !== undefined && (!next.match(/^-/) || - next.match(negative)) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next); - i++; - } - else { - setArg(key, defaultValue(key)); - } - } - } - // dot-notation flag separated by '='. - } - else if (arg.match(/^-.\..+=/)) { - m = arg.match(/^-([^=]+)=([\s\S]*)$/); - if (m !== null && Array.isArray(m) && m.length >= 3) { - setArg(m[1], m[2]); - } - // dot-notation flag separated by space. - } - else if (arg.match(/^-.\..+/) && !arg.match(negative)) { - next = args[i + 1]; - m = arg.match(/^-(.\..+)/); - if (m !== null && Array.isArray(m) && m.length >= 2) { - key = m[1]; - if (next !== undefined && !next.match(/^-/) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next); - i++; - } - else { - setArg(key, defaultValue(key)); - } - } - } - else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { - letters = arg.slice(1, -1).split(''); - broken = false; - for (let j = 0; j < letters.length; j++) { - next = arg.slice(j + 2); - if (letters[j + 1] && letters[j + 1] === '=') { - value = arg.slice(j + 3); - key = letters[j]; - if (checkAllAliases(key, flags.arrays)) { - // array format = '-f=a b c' - i = eatArray(i, key, args, value); - } - else if (checkAllAliases(key, flags.nargs) !== false) { - // nargs format = '-f=monkey washing cat' - i = eatNargs(i, key, args, value); - } - else { - setArg(key, value); - } - broken = true; - break; - } - if (next === '-') { - setArg(letters[j], next); - continue; - } - // current letter is an alphabetic character and next value is a number - if (/[A-Za-z]/.test(letters[j]) && - /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && - checkAllAliases(next, flags.bools) === false) { - setArg(letters[j], next); - broken = true; - break; - } - if (letters[j + 1] && letters[j + 1].match(/\W/)) { - setArg(letters[j], next); - broken = true; - break; - } - else { - setArg(letters[j], defaultValue(letters[j])); - } - } - key = arg.slice(-1)[0]; - if (!broken && key !== '-') { - if (checkAllAliases(key, flags.arrays)) { - // array format = '-f a b c' - i = eatArray(i, key, args); - } - else if (checkAllAliases(key, flags.nargs) !== false) { - // nargs format = '-f a b c' - // should be truthy even if: flags.nargs[key] === 0 - i = eatNargs(i, key, args); - } - else { - next = args[i + 1]; - if (next !== undefined && (!/^(-|--)[^-]/.test(next) || - next.match(negative)) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next); - i++; - } - else { - setArg(key, defaultValue(key)); - } - } - } - } - else if (arg.match(/^-[0-9]$/) && - arg.match(negative) && - checkAllAliases(arg.slice(1), flags.bools)) { - // single-digit boolean alias, e.g: xargs -0 - key = arg.slice(1); - setArg(key, defaultValue(key)); - } - else if (arg === '--') { - notFlags = args.slice(i + 1); - break; - } - else if (configuration['halt-at-non-option']) { - notFlags = args.slice(i); - break; - } - else { - pushPositional(arg); - } - } - // order of precedence: - // 1. command line arg - // 2. value from env var - // 3. value from config file - // 4. value from config objects - // 5. configured default value - applyEnvVars(argv, true); // special case: check env vars that point to config file - applyEnvVars(argv, false); - setConfig(argv); - setConfigObjects(); - applyDefaultsAndAliases(argv, flags.aliases, defaults, true); - applyCoercions(argv); - if (configuration['set-placeholder-key']) - setPlaceholderKeys(argv); - // for any counts either not in args or without an explicit default, set to 0 - Object.keys(flags.counts).forEach(function (key) { - if (!hasKey(argv, key.split('.'))) - setArg(key, 0); - }); - // '--' defaults to undefined. - if (notFlagsOption && notFlags.length) - argv[notFlagsArgv] = []; - notFlags.forEach(function (key) { - argv[notFlagsArgv].push(key); - }); - if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { - Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { - delete argv[key]; - }); - } - if (configuration['strip-aliased']) { - [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { - if (configuration['camel-case-expansion'] && alias.includes('-')) { - delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; - } - delete argv[alias]; - }); - } - // Push argument into positional array, applying numeric coercion: - function pushPositional(arg) { - const maybeCoercedNumber = maybeCoerceNumber('_', arg); - if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { - argv._.push(maybeCoercedNumber); - } - } - // how many arguments should we consume, based - // on the nargs option? - function eatNargs(i, key, args, argAfterEqualSign) { - let ii; - let toEat = checkAllAliases(key, flags.nargs); - // NaN has a special meaning for the array type, indicating that one or - // more values are expected. - toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; - if (toEat === 0) { - if (!isUndefined(argAfterEqualSign)) { - error = Error(__('Argument unexpected for: %s', key)); - } - setArg(key, defaultValue(key)); - return i; - } - let available = isUndefined(argAfterEqualSign) ? 0 : 1; - if (configuration['nargs-eats-options']) { - // classic behavior, yargs eats positional and dash arguments. - if (args.length - (i + 1) + available < toEat) { - error = Error(__('Not enough arguments following: %s', key)); - } - available = toEat; - } - else { - // nargs will not consume flag arguments, e.g., -abc, --foo, - // and terminates when one is observed. - for (ii = i + 1; ii < args.length; ii++) { - if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) - available++; - else - break; - } - if (available < toEat) - error = Error(__('Not enough arguments following: %s', key)); - } - let consumed = Math.min(available, toEat); - if (!isUndefined(argAfterEqualSign) && consumed > 0) { - setArg(key, argAfterEqualSign); - consumed--; - } - for (ii = i + 1; ii < (consumed + i + 1); ii++) { - setArg(key, args[ii]); - } - return (i + consumed); - } - // if an option is an array, eat all non-hyphenated arguments - // following it... YUM! - // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] - function eatArray(i, key, args, argAfterEqualSign) { - let argsToSet = []; - let next = argAfterEqualSign || args[i + 1]; - // If both array and nargs are configured, enforce the nargs count: - const nargsCount = checkAllAliases(key, flags.nargs); - if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { - argsToSet.push(true); - } - else if (isUndefined(next) || - (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { - // for keys without value ==> argsToSet remains an empty [] - // set user default value, if available - if (defaults[key] !== undefined) { - const defVal = defaults[key]; - argsToSet = Array.isArray(defVal) ? defVal : [defVal]; - } - } - else { - // value in --option=value is eaten as is - if (!isUndefined(argAfterEqualSign)) { - argsToSet.push(processValue(key, argAfterEqualSign, true)); - } - for (let ii = i + 1; ii < args.length; ii++) { - if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || - (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) - break; - next = args[ii]; - if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) - break; - i = ii; - argsToSet.push(processValue(key, next, inputIsString)); - } - } - // If both array and nargs are configured, create an error if less than - // nargs positionals were found. NaN has special meaning, indicating - // that at least one value is required (more are okay). - if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || - (isNaN(nargsCount) && argsToSet.length === 0))) { - error = Error(__('Not enough arguments following: %s', key)); - } - setArg(key, argsToSet); - return i; - } - function setArg(key, val, shouldStripQuotes = inputIsString) { - if (/-/.test(key) && configuration['camel-case-expansion']) { - const alias = key.split('.').map(function (prop) { - return camelCase(prop); - }).join('.'); - addNewAlias(key, alias); - } - const value = processValue(key, val, shouldStripQuotes); - const splitKey = key.split('.'); - setKey(argv, splitKey, value); - // handle populating aliases of the full key - if (flags.aliases[key]) { - flags.aliases[key].forEach(function (x) { - const keyProperties = x.split('.'); - setKey(argv, keyProperties, value); - }); - } - // handle populating aliases of the first element of the dot-notation key - if (splitKey.length > 1 && configuration['dot-notation']) { - (flags.aliases[splitKey[0]] || []).forEach(function (x) { - let keyProperties = x.split('.'); - // expand alias with nested objects in key - const a = [].concat(splitKey); - a.shift(); // nuke the old key. - keyProperties = keyProperties.concat(a); - // populate alias only if is not already an alias of the full key - // (already populated above) - if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { - setKey(argv, keyProperties, value); - } - }); - } - // Set normalize getter and setter when key is in 'normalize' but isn't an array - if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { - const keys = [key].concat(flags.aliases[key] || []); - keys.forEach(function (key) { - Object.defineProperty(argvReturn, key, { - enumerable: true, - get() { - return val; - }, - set(value) { - val = typeof value === 'string' ? mixin.normalize(value) : value; - } - }); - }); - } - } - function addNewAlias(key, alias) { - if (!(flags.aliases[key] && flags.aliases[key].length)) { - flags.aliases[key] = [alias]; - newAliases[alias] = true; - } - if (!(flags.aliases[alias] && flags.aliases[alias].length)) { - addNewAlias(alias, key); - } - } - function processValue(key, val, shouldStripQuotes) { - // strings may be quoted, clean this up as we assign values. - if (shouldStripQuotes) { - val = stripQuotes(val); - } - // handle parsing boolean arguments --foo=true --bar false. - if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { - if (typeof val === 'string') - val = val === 'true'; - } - let value = Array.isArray(val) - ? val.map(function (v) { return maybeCoerceNumber(key, v); }) - : maybeCoerceNumber(key, val); - // increment a count given as arg (either no value or value parsed as boolean) - if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { - value = increment(); - } - // Set normalized value when key is in 'normalize' and in 'arrays' - if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { - if (Array.isArray(val)) - value = val.map((val) => { return mixin.normalize(val); }); - else - value = mixin.normalize(val); - } - return value; - } - function maybeCoerceNumber(key, value) { - if (!configuration['parse-positional-numbers'] && key === '_') - return value; - if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { - const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); - if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { - value = Number(value); - } - } - return value; - } - // set args from config.json file, this should be - // applied last so that defaults can be applied. - function setConfig(argv) { - const configLookup = Object.create(null); - // expand defaults/aliases, in-case any happen to reference - // the config.json file. - applyDefaultsAndAliases(configLookup, flags.aliases, defaults); - Object.keys(flags.configs).forEach(function (configKey) { - const configPath = argv[configKey] || configLookup[configKey]; - if (configPath) { - try { - let config = null; - const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); - const resolveConfig = flags.configs[configKey]; - if (typeof resolveConfig === 'function') { - try { - config = resolveConfig(resolvedConfigPath); - } - catch (e) { - config = e; - } - if (config instanceof Error) { - error = config; - return; - } - } - else { - config = mixin.require(resolvedConfigPath); - } - setConfigObject(config); - } - catch (ex) { - // Deno will receive a PermissionDenied error if an attempt is - // made to load config without the --allow-read flag: - if (ex.name === 'PermissionDenied') - error = ex; - else if (argv[configKey]) - error = Error(__('Invalid JSON config file: %s', configPath)); - } - } - }); - } - // set args from config object. - // it recursively checks nested objects. - function setConfigObject(config, prev) { - Object.keys(config).forEach(function (key) { - const value = config[key]; - const fullKey = prev ? prev + '.' + key : key; - // if the value is an inner object and we have dot-notation - // enabled, treat inner objects in config the same as - // heavily nested dot notations (foo.bar.apple). - if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { - // if the value is an object but not an array, check nested object - setConfigObject(value, fullKey); - } - else { - // setting arguments via CLI takes precedence over - // values within the config file. - if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { - setArg(fullKey, value); - } - } - }); - } - // set all config objects passed in opts - function setConfigObjects() { - if (typeof configObjects !== 'undefined') { - configObjects.forEach(function (configObject) { - setConfigObject(configObject); - }); - } - } - function applyEnvVars(argv, configOnly) { - if (typeof envPrefix === 'undefined') - return; - const prefix = typeof envPrefix === 'string' ? envPrefix : ''; - const env = mixin.env(); - Object.keys(env).forEach(function (envVar) { - if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { - // get array of nested keys and convert them to camel case - const keys = envVar.split('__').map(function (key, i) { - if (i === 0) { - key = key.substring(prefix.length); - } - return camelCase(key); - }); - if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { - setArg(keys.join('.'), env[envVar]); - } - } - }); - } - function applyCoercions(argv) { - let coerce; - const applied = new Set(); - Object.keys(argv).forEach(function (key) { - if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases - coerce = checkAllAliases(key, flags.coercions); - if (typeof coerce === 'function') { - try { - const value = maybeCoerceNumber(key, coerce(argv[key])); - ([].concat(flags.aliases[key] || [], key)).forEach(ali => { - applied.add(ali); - argv[ali] = value; - }); - } - catch (err) { - error = err; - } - } - } - }); - } - function setPlaceholderKeys(argv) { - flags.keys.forEach((key) => { - // don't set placeholder keys for dot notation options 'foo.bar'. - if (~key.indexOf('.')) - return; - if (typeof argv[key] === 'undefined') - argv[key] = undefined; - }); - return argv; - } - function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { - Object.keys(defaults).forEach(function (key) { - if (!hasKey(obj, key.split('.'))) { - setKey(obj, key.split('.'), defaults[key]); - if (canLog) - defaulted[key] = true; - (aliases[key] || []).forEach(function (x) { - if (hasKey(obj, x.split('.'))) - return; - setKey(obj, x.split('.'), defaults[key]); - }); - } - }); - } - function hasKey(obj, keys) { - let o = obj; - if (!configuration['dot-notation']) - keys = [keys.join('.')]; - keys.slice(0, -1).forEach(function (key) { - o = (o[key] || {}); - }); - const key = keys[keys.length - 1]; - if (typeof o !== 'object') - return false; - else - return key in o; - } - function setKey(obj, keys, value) { - let o = obj; - if (!configuration['dot-notation']) - keys = [keys.join('.')]; - keys.slice(0, -1).forEach(function (key) { - // TODO(bcoe): in the next major version of yargs, switch to - // Object.create(null) for dot notation: - key = sanitizeKey(key); - if (typeof o === 'object' && o[key] === undefined) { - o[key] = {}; - } - if (typeof o[key] !== 'object' || Array.isArray(o[key])) { - // ensure that o[key] is an array, and that the last item is an empty object. - if (Array.isArray(o[key])) { - o[key].push({}); - } - else { - o[key] = [o[key], {}]; - } - // we want to update the empty object at the end of the o[key] array, so set o to that object - o = o[key][o[key].length - 1]; - } - else { - o = o[key]; - } - }); - // TODO(bcoe): in the next major version of yargs, switch to - // Object.create(null) for dot notation: - const key = sanitizeKey(keys[keys.length - 1]); - const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); - const isValueArray = Array.isArray(value); - let duplicate = configuration['duplicate-arguments-array']; - // nargs has higher priority than duplicate - if (!duplicate && checkAllAliases(key, flags.nargs)) { - duplicate = true; - if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { - o[key] = undefined; - } - } - if (value === increment()) { - o[key] = increment(o[key]); - } - else if (Array.isArray(o[key])) { - if (duplicate && isTypeArray && isValueArray) { - o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); - } - else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { - o[key] = value; - } - else { - o[key] = o[key].concat([value]); - } - } - else if (o[key] === undefined && isTypeArray) { - o[key] = isValueArray ? value : [value]; - } - else if (duplicate && !(o[key] === undefined || - checkAllAliases(key, flags.counts) || - checkAllAliases(key, flags.bools))) { - o[key] = [o[key], value]; - } - else { - o[key] = value; - } - } - // extend the aliases list with inferred aliases. - function extendAliases(...args) { - args.forEach(function (obj) { - Object.keys(obj || {}).forEach(function (key) { - // short-circuit if we've already added a key - // to the aliases array, for example it might - // exist in both 'opts.default' and 'opts.key'. - if (flags.aliases[key]) - return; - flags.aliases[key] = [].concat(aliases[key] || []); - // For "--option-name", also set argv.optionName - flags.aliases[key].concat(key).forEach(function (x) { - if (/-/.test(x) && configuration['camel-case-expansion']) { - const c = camelCase(x); - if (c !== key && flags.aliases[key].indexOf(c) === -1) { - flags.aliases[key].push(c); - newAliases[c] = true; - } - } - }); - // For "--optionName", also set argv['option-name'] - flags.aliases[key].concat(key).forEach(function (x) { - if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { - const c = decamelize(x, '-'); - if (c !== key && flags.aliases[key].indexOf(c) === -1) { - flags.aliases[key].push(c); - newAliases[c] = true; - } - } - }); - flags.aliases[key].forEach(function (x) { - flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { - return x !== y; - })); - }); - }); - }); - } - function checkAllAliases(key, flag) { - const toCheck = [].concat(flags.aliases[key] || [], key); - const keys = Object.keys(flag); - const setAlias = toCheck.find(key => keys.includes(key)); - return setAlias ? flag[setAlias] : false; - } - function hasAnyFlag(key) { - const flagsKeys = Object.keys(flags); - const toCheck = [].concat(flagsKeys.map(k => flags[k])); - return toCheck.some(function (flag) { - return Array.isArray(flag) ? flag.includes(key) : flag[key]; - }); - } - function hasFlagsMatching(arg, ...patterns) { - const toCheck = [].concat(...patterns); - return toCheck.some(function (pattern) { - const match = arg.match(pattern); - return match && hasAnyFlag(match[1]); - }); - } - // based on a simplified version of the short flag group parsing logic - function hasAllShortFlags(arg) { - // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group - if (arg.match(negative) || !arg.match(/^-[^-]+/)) { - return false; - } - let hasAllFlags = true; - let next; - const letters = arg.slice(1).split(''); - for (let j = 0; j < letters.length; j++) { - next = arg.slice(j + 2); - if (!hasAnyFlag(letters[j])) { - hasAllFlags = false; - break; - } - if ((letters[j + 1] && letters[j + 1] === '=') || - next === '-' || - (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || - (letters[j + 1] && letters[j + 1].match(/\W/))) { - break; - } - } - return hasAllFlags; - } - function isUnknownOptionAsArg(arg) { - return configuration['unknown-options-as-args'] && isUnknownOption(arg); - } - function isUnknownOption(arg) { - arg = arg.replace(/^-{3,}/, '--'); - // ignore negative numbers - if (arg.match(negative)) { - return false; - } - // if this is a short option group and all of them are configured, it isn't unknown - if (hasAllShortFlags(arg)) { - return false; - } - // e.g. '--count=2' - const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; - // e.g. '-a' or '--arg' - const normalFlag = /^-+([^=]+?)$/; - // e.g. '-a-' - const flagEndingInHyphen = /^-+([^=]+?)-$/; - // e.g. '-abc123' - const flagEndingInDigits = /^-+([^=]+?\d+)$/; - // e.g. '-a/usr/local' - const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; - // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method - return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); - } - // make a best effort to pick a default value - // for an option based on name and type. - function defaultValue(key) { - if (!checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts) && - `${key}` in defaults) { - return defaults[key]; - } - else { - return defaultForType(guessType(key)); - } - } - // return a default value, given the type of a flag., - function defaultForType(type) { - const def = { - [DefaultValuesForTypeKey.BOOLEAN]: true, - [DefaultValuesForTypeKey.STRING]: '', - [DefaultValuesForTypeKey.NUMBER]: undefined, - [DefaultValuesForTypeKey.ARRAY]: [] - }; - return def[type]; - } - // given a flag, enforce a default type. - function guessType(key) { - let type = DefaultValuesForTypeKey.BOOLEAN; - if (checkAllAliases(key, flags.strings)) - type = DefaultValuesForTypeKey.STRING; - else if (checkAllAliases(key, flags.numbers)) - type = DefaultValuesForTypeKey.NUMBER; - else if (checkAllAliases(key, flags.bools)) - type = DefaultValuesForTypeKey.BOOLEAN; - else if (checkAllAliases(key, flags.arrays)) - type = DefaultValuesForTypeKey.ARRAY; - return type; - } - function isUndefined(num) { - return num === undefined; - } - // check user configuration settings for inconsistencies - function checkConfiguration() { - // count keys should not be set as array/narg - Object.keys(flags.counts).find(key => { - if (checkAllAliases(key, flags.arrays)) { - error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); - return true; - } - else if (checkAllAliases(key, flags.nargs)) { - error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); - return true; - } - return false; - }); - } - return { - aliases: Object.assign({}, flags.aliases), - argv: Object.assign(argvReturn, argv), - configuration: configuration, - defaulted: Object.assign({}, defaulted), - error: error, - newAliases: Object.assign({}, newAliases) - }; - } -} -// if any aliases reference each other, we should -// merge them together. -function combineAliases(aliases) { - const aliasArrays = []; - const combined = Object.create(null); - let change = true; - // turn alias lookup hash {key: ['alias1', 'alias2']} into - // a simple array ['key', 'alias1', 'alias2'] - Object.keys(aliases).forEach(function (key) { - aliasArrays.push([].concat(aliases[key], key)); - }); - // combine arrays until zero changes are - // made in an iteration. - while (change) { - change = false; - for (let i = 0; i < aliasArrays.length; i++) { - for (let ii = i + 1; ii < aliasArrays.length; ii++) { - const intersect = aliasArrays[i].filter(function (v) { - return aliasArrays[ii].indexOf(v) !== -1; - }); - if (intersect.length) { - aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); - aliasArrays.splice(ii, 1); - change = true; - break; - } - } - } - } - // map arrays back to the hash-lookup (de-dupe while - // we're at it). - aliasArrays.forEach(function (aliasArray) { - aliasArray = aliasArray.filter(function (v, i, self) { - return self.indexOf(v) === i; - }); - const lastAlias = aliasArray.pop(); - if (lastAlias !== undefined && typeof lastAlias === 'string') { - combined[lastAlias] = aliasArray; - } - }); - return combined; -} -// this function should only be called when a count is given as an arg -// it is NOT called to set a default value -// thus we can start the count at 1 instead of 0 -function increment(orig) { - return orig !== undefined ? orig + 1 : 1; -} -// TODO(bcoe): in the next major version of yargs, switch to -// Object.create(null) for dot notation: -function sanitizeKey(key) { - if (key === '__proto__') - return '___proto___'; - return key; -} -function stripQuotes(val) { - return (typeof val === 'string' && - (val[0] === "'" || val[0] === '"') && - val[val.length - 1] === val[0]) - ? val.substring(1, val.length - 1) - : val; -} - -/** - * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js - * CJS and ESM environments. - * - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -var _a, _b, _c; -// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our -// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only. -const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) - ? Number(process.env.YARGS_MIN_NODE_VERSION) - : 12; -const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1); -if (nodeVersion) { - const major = Number(nodeVersion.match(/^([^.]+)/)[1]); - if (major < minNodeVersion) { - throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); - } -} -// Creates a yargs-parser instance using Node.js standard libraries: -const env = process ? process.env : {}; -const parser = new YargsParser({ - cwd: process.cwd, - env: () => { - return env; - }, - format: require$$2.format, - normalize: require$$0.normalize, - resolve: require$$0.resolve, - // TODO: figure out a way to combine ESM and CJS coverage, such that - // we can exercise all the lines below: - require: (path) => { - if (typeof require !== 'undefined') { - return require(path); - } - else if (path.match(/\.json$/)) { - // Addresses: https://github.com/yargs/yargs/issues/2040 - return JSON.parse(require$$0$1.readFileSync(path, 'utf8')); - } - else { - throw Error('only .json config files are supported in ESM'); - } - } -}); -const yargsParser = function Parser(args, opts) { - const result = parser.parse(args.slice(), opts); - return result.argv; -}; -yargsParser.detailed = function (args, opts) { - return parser.parse(args.slice(), opts); -}; -yargsParser.camelCase = camelCase; -yargsParser.decamelize = decamelize; -yargsParser.looksLikeNumber = looksLikeNumber; - -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ - - -function __addDisposableResource(env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; - env.stack.push({ value: value, dispose: dispose, async: async }); - } - else if (async) { - env.stack.push({ async: true }); - } - return value; - -} - -var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}; - -function __disposeResources(env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); - } - else s |= 1; - } - catch (e) { - fail(e); - } - } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; - } - return next(); -} - -const toZeroIfInfinity = value => Number.isFinite(value) ? value : 0; - -function parseNumber(milliseconds) { - return { - days: Math.trunc(milliseconds / 86_400_000), - hours: Math.trunc(milliseconds / 3_600_000 % 24), - minutes: Math.trunc(milliseconds / 60_000 % 60), - seconds: Math.trunc(milliseconds / 1000 % 60), - milliseconds: Math.trunc(milliseconds % 1000), - microseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1000) % 1000), - nanoseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e6) % 1000), - }; -} - -function parseBigint(milliseconds) { - return { - days: milliseconds / 86_400_000n, - hours: milliseconds / 3_600_000n % 24n, - minutes: milliseconds / 60_000n % 60n, - seconds: milliseconds / 1000n % 60n, - milliseconds: milliseconds % 1000n, - microseconds: 0n, - nanoseconds: 0n, - }; -} - -function parseMilliseconds(milliseconds) { - switch (typeof milliseconds) { - case 'number': { - if (Number.isFinite(milliseconds)) { - return parseNumber(milliseconds); - } - - break; - } - - case 'bigint': { - return parseBigint(milliseconds); - } - - // No default - } - - throw new TypeError('Expected a finite number or bigint'); -} - -const isZero = value => value === 0 || value === 0n; -const pluralize = (word, count) => (count === 1 || count === 1n) ? word : `${word}s`; - -const SECOND_ROUNDING_EPSILON = 0.000_000_1; -const ONE_DAY_IN_MILLISECONDS = 24n * 60n * 60n * 1000n; - -function prettyMilliseconds(milliseconds, options) { - const isBigInt = typeof milliseconds === 'bigint'; - if (!isBigInt && !Number.isFinite(milliseconds)) { - throw new TypeError('Expected a finite number or bigint'); - } - - options = {...options}; - - const sign = milliseconds < 0 ? '-' : ''; - milliseconds = milliseconds < 0 ? -milliseconds : milliseconds; // Cannot use `Math.abs()` because of BigInt support. - - if (options.colonNotation) { - options.compact = false; - options.formatSubMilliseconds = false; - options.separateMilliseconds = false; - options.verbose = false; - } - - if (options.compact) { - options.unitCount = 1; - options.secondsDecimalDigits = 0; - options.millisecondsDecimalDigits = 0; - } - - let result = []; - - const floorDecimals = (value, decimalDigits) => { - const flooredInterimValue = Math.floor((value * (10 ** decimalDigits)) + SECOND_ROUNDING_EPSILON); - const flooredValue = Math.round(flooredInterimValue) / (10 ** decimalDigits); - return flooredValue.toFixed(decimalDigits); - }; - - const add = (value, long, short, valueString) => { - if ( - (result.length === 0 || !options.colonNotation) - && isZero(value) - && !(options.colonNotation && short === 'm')) { - return; - } - - valueString ??= String(value); - if (options.colonNotation) { - const wholeDigits = valueString.includes('.') ? valueString.split('.')[0].length : valueString.length; - const minLength = result.length > 0 ? 2 : 1; - valueString = '0'.repeat(Math.max(0, minLength - wholeDigits)) + valueString; - } else { - valueString += options.verbose ? ' ' + pluralize(long, value) : short; - } - - result.push(valueString); - }; - - const parsed = parseMilliseconds(milliseconds); - const days = BigInt(parsed.days); - - if (options.hideYearAndDays) { - add((BigInt(days) * 24n) + BigInt(parsed.hours), 'hour', 'h'); - } else { - if (options.hideYear) { - add(days, 'day', 'd'); - } else { - add(days / 365n, 'year', 'y'); - add(days % 365n, 'day', 'd'); - } - - add(Number(parsed.hours), 'hour', 'h'); - } - - add(Number(parsed.minutes), 'minute', 'm'); - - if (!options.hideSeconds) { - if ( - options.separateMilliseconds - || options.formatSubMilliseconds - || (!options.colonNotation && milliseconds < 1000) - ) { - const seconds = Number(parsed.seconds); - const milliseconds = Number(parsed.milliseconds); - const microseconds = Number(parsed.microseconds); - const nanoseconds = Number(parsed.nanoseconds); - - add(seconds, 'second', 's'); - - if (options.formatSubMilliseconds) { - add(milliseconds, 'millisecond', 'ms'); - add(microseconds, 'microsecond', 'µs'); - add(nanoseconds, 'nanosecond', 'ns'); - } else { - const millisecondsAndBelow - = milliseconds - + (microseconds / 1000) - + (nanoseconds / 1e6); - - const millisecondsDecimalDigits - = typeof options.millisecondsDecimalDigits === 'number' - ? options.millisecondsDecimalDigits - : 0; - - const roundedMilliseconds = millisecondsAndBelow >= 1 - ? Math.round(millisecondsAndBelow) - : Math.ceil(millisecondsAndBelow); - - const millisecondsString = millisecondsDecimalDigits - ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits) - : roundedMilliseconds; - - add( - Number.parseFloat(millisecondsString), - 'millisecond', - 'ms', - millisecondsString, - ); - } - } else { - const seconds = ( - (isBigInt ? Number(milliseconds % ONE_DAY_IN_MILLISECONDS) : milliseconds) - / 1000 - ) % 60; - const secondsDecimalDigits - = typeof options.secondsDecimalDigits === 'number' - ? options.secondsDecimalDigits - : 1; - const secondsFixed = floorDecimals(seconds, secondsDecimalDigits); - const secondsString = options.keepDecimalsOnWholeSeconds - ? secondsFixed - : secondsFixed.replace(/\.0+$/, ''); - add(Number.parseFloat(secondsString), 'second', 's', secondsString); - } - } - - if (result.length === 0) { - return sign + '0' + (options.verbose ? ' milliseconds' : 'ms'); - } - - const separator = options.colonNotation ? ':' : ' '; - if (typeof options.unitCount === 'number') { - result = result.slice(0, Math.max(options.unitCount, 1)); - } - - return sign + result.join(separator); -} - -const BYTE_UNITS = [ - 'B', - 'kB', - 'MB', - 'GB', - 'TB', - 'PB', - 'EB', - 'ZB', - 'YB', -]; - -const BIBYTE_UNITS = [ - 'B', - 'KiB', - 'MiB', - 'GiB', - 'TiB', - 'PiB', - 'EiB', - 'ZiB', - 'YiB', -]; - -const BIT_UNITS = [ - 'b', - 'kbit', - 'Mbit', - 'Gbit', - 'Tbit', - 'Pbit', - 'Ebit', - 'Zbit', - 'Ybit', -]; - -const BIBIT_UNITS = [ - 'b', - 'kibit', - 'Mibit', - 'Gibit', - 'Tibit', - 'Pibit', - 'Eibit', - 'Zibit', - 'Yibit', -]; - -/* -Formats the given number using `Number#toLocaleString`. -- If locale is a string, the value is expected to be a locale-key (for example: `de`). -- If locale is true, the system default locale is used for translation. -- If no value for locale is specified, the number is returned unmodified. -*/ -const toLocaleString = (number, locale, options) => { - let result = number; - if (typeof locale === 'string' || Array.isArray(locale)) { - result = number.toLocaleString(locale, options); - } else if (locale === true || options !== undefined) { - result = number.toLocaleString(undefined, options); - } - - return result; -}; - -const log10 = numberOrBigInt => { - if (typeof numberOrBigInt === 'number') { - return Math.log10(numberOrBigInt); - } - - const string = numberOrBigInt.toString(10); - - return string.length + Math.log10('0.' + string.slice(0, 15)); -}; - -const log = numberOrBigInt => { - if (typeof numberOrBigInt === 'number') { - return Math.log(numberOrBigInt); - } - - return log10(numberOrBigInt) * Math.log(10); -}; - -const divide = (numberOrBigInt, divisor) => { - if (typeof numberOrBigInt === 'number') { - return numberOrBigInt / divisor; - } - - const integerPart = numberOrBigInt / BigInt(divisor); - const remainder = numberOrBigInt % BigInt(divisor); - return Number(integerPart) + (Number(remainder) / divisor); -}; - -function prettyBytes(number, options) { - if (typeof number !== 'bigint' && !Number.isFinite(number)) { - throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`); - } - - options = { - bits: false, - binary: false, - space: true, - ...options, - }; - - const UNITS = options.bits - ? (options.binary ? BIBIT_UNITS : BIT_UNITS) - : (options.binary ? BIBYTE_UNITS : BYTE_UNITS); - - const separator = options.space ? ' ' : ''; - - if (options.signed && (typeof number === 'number' ? number === 0 : number === 0n)) { - return ` 0${separator}${UNITS[0]}`; - } - - const isNegative = number < 0; - const prefix = isNegative ? '-' : (options.signed ? '+' : ''); - - if (isNegative) { - number = -number; - } - - let localeOptions; - - if (options.minimumFractionDigits !== undefined) { - localeOptions = {minimumFractionDigits: options.minimumFractionDigits}; - } - - if (options.maximumFractionDigits !== undefined) { - localeOptions = {maximumFractionDigits: options.maximumFractionDigits, ...localeOptions}; - } - - if (number < 1) { - const numberString = toLocaleString(number, options.locale, localeOptions); - return prefix + numberString + separator + UNITS[0]; - } - - const exponent = Math.min(Math.floor(options.binary ? log(number) / Math.log(1024) : log10(number) / 3), UNITS.length - 1); - number = divide(number, (options.binary ? 1024 : 1000) ** exponent); - - if (!localeOptions) { - number = number.toPrecision(3); - } - - const numberString = toLocaleString(Number(number), options.locale, localeOptions); - - const unit = UNITS[exponent]; - - return prefix + numberString + separator + unit; -} - -function printTimings(timings) { - for (const [label, [time, memory, total]] of Object.entries(timings)) { - const appliedColor = label[0] === '#' ? (label[1] === '#' ? rollup.bold : rollup.underline) : (text) => text; - const row = `${label}: ${time.toFixed(0)}ms, ${prettyBytes(memory)} / ${prettyBytes(total)}`; - console.info(appliedColor(row)); - } -} - -async function build(inputOptions, warnings, silent = false) { - const env_1 = { stack: [], error: void 0, hasError: false }; - try { - const outputOptions = inputOptions.output; - const useStdout = !outputOptions[0].file && !outputOptions[0].dir; - const start = Date.now(); - const files = useStdout ? ['stdout'] : outputOptions.map(t => parseAst_js.relativeId(t.file || t.dir)); - if (!silent) { - let inputFiles; - if (typeof inputOptions.input === 'string') { - inputFiles = inputOptions.input; - } - else if (Array.isArray(inputOptions.input)) { - inputFiles = inputOptions.input.join(', '); - } - else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) { - inputFiles = Object.values(inputOptions.input).join(', '); - } - rollup.stderr(rollup.cyan(`\n${rollup.bold(inputFiles)} → ${rollup.bold(files.join(', '))}...`)); - } - const bundle = __addDisposableResource(env_1, await rollup.rollup(inputOptions), true); - if (useStdout) { - const output = outputOptions[0]; - if (output.sourcemap && output.sourcemap !== 'inline') { - rollup.handleError(parseAst_js.logOnlyInlineSourcemapsForStdout()); - } - const { output: outputs } = await bundle.generate(output); - for (const file of outputs) { - if (outputs.length > 1) - process$1.stdout.write(`\n${rollup.cyan(rollup.bold(`//→ ${file.fileName}:`))}\n`); - process$1.stdout.write(file.type === 'asset' ? file.source : file.code); - } - if (!silent) { - warnings.flush(); - } - return; - } - await Promise.all(outputOptions.map(bundle.write)); - if (!silent) { - warnings.flush(); - rollup.stderr(rollup.green(`created ${rollup.bold(files.join(', '))} in ${rollup.bold(prettyMilliseconds(Date.now() - start))}`)); - if (bundle && bundle.getTimings) { - printTimings(bundle.getTimings()); - } - } - } - catch (e_1) { - env_1.error = e_1; - env_1.hasError = true; - } - finally { - const result_1 = __disposeResources(env_1); - if (result_1) - await result_1; - } -} - -const DEFAULT_CONFIG_BASE = 'rollup.config'; -async function getConfigPath(commandConfig) { - if (commandConfig === true) { - return path.resolve(await findConfigFileNameInCwd()); - } - if (commandConfig.slice(0, 5) === 'node:') { - const packageName = commandConfig.slice(5); - try { - return require.resolve(`rollup-config-${packageName}`, { paths: [process$1.cwd()] }); - } - catch { - try { - return require.resolve(packageName, { paths: [process$1.cwd()] }); - } - catch (error) { - if (error.code === 'MODULE_NOT_FOUND') { - rollup.handleError(parseAst_js.logMissingExternalConfig(commandConfig)); - } - throw error; - } - } - } - return path.resolve(commandConfig); -} -async function findConfigFileNameInCwd() { - const filesInWorkingDirectory = new Set(await promises.readdir(process$1.cwd())); - for (const extension of ['mjs', 'cjs', 'ts']) { - const fileName = `${DEFAULT_CONFIG_BASE}.${extension}`; - if (filesInWorkingDirectory.has(fileName)) - return fileName; - } - return `${DEFAULT_CONFIG_BASE}.js`; -} - -async function loadConfigFromCommand(commandOptions, watchMode) { - const warnings = loadConfigFile_js.batchWarnings(commandOptions); - if (!commandOptions.input && (commandOptions.stdin || !process$1.stdin.isTTY)) { - commandOptions.input = loadConfigFile_js.stdinName; - } - const options = await rollup.mergeOptions({ input: [] }, watchMode, commandOptions, warnings.log); - await loadConfigFile_js.addCommandPluginsToInputOptions(options, commandOptions); - return { options: [options], warnings }; -} - -async function runRollup(command) { - let inputSource; - if (command._.length > 0) { - if (command.input) { - rollup.handleError(parseAst_js.logDuplicateImportOptions()); - } - inputSource = command._; - } - else if (typeof command.input === 'string') { - inputSource = [command.input]; - } - else { - inputSource = command.input; - } - if (inputSource && inputSource.length > 0) { - if (inputSource.some((input) => input.includes('='))) { - command.input = {}; - for (const input of inputSource) { - const equalsIndex = input.indexOf('='); - const value = input.slice(Math.max(0, equalsIndex + 1)); - const key = input.slice(0, Math.max(0, equalsIndex)) || parseAst_js.getAliasName(input); - command.input[key] = value; - } - } - else { - command.input = inputSource; - } - } - if (command.environment) { - const environment = Array.isArray(command.environment) - ? command.environment - : [command.environment]; - for (const argument of environment) { - for (const pair of argument.split(',')) { - const [key, ...value] = pair.split(':'); - process$1.env[key] = value.length === 0 ? String(true) : value.join(':'); - } - } - } - if (rollup.isWatchEnabled(command.watch)) { - await fseventsImporter.loadFsEvents(); - const { watch } = await Promise.resolve().then(() => require('../shared/watch-cli.js')); - await watch(command); - } - else { - try { - const { options, warnings } = await getConfigs(command); - try { - for (const inputOptions of options) { - if (!inputOptions.cache) { - // We explicitly disable the cache when unused as the CLI will not - // use the cache object on the bundle when not in watch mode. This - // improves performance as the cache is not generated. - inputOptions.cache = false; - } - await build(inputOptions, warnings, command.silent); - } - if (command.failAfterWarnings && warnings.warningOccurred) { - warnings.flush(); - rollup.handleError(parseAst_js.logFailAfterWarnings()); - } - } - catch (error) { - warnings.flush(); - rollup.handleError(error); - } - } - catch (error) { - rollup.handleError(error); - } - } -} -async function getConfigs(command) { - if (command.config) { - const configFile = await getConfigPath(command.config); - const { options, warnings } = await loadConfigFile_js.loadConfigFile(configFile, command, false); - return { options, warnings }; - } - return await loadConfigFromCommand(command, false); -} - -const command = yargsParser(process$1.argv.slice(2), { - alias: rollup.commandAliases, - configuration: { 'camel-case-expansion': false } -}); -if (command.help || (process$1.argv.length <= 2 && process$1.stdin.isTTY)) { - console.log(`\n${help.replace('__VERSION__', rollup.version)}\n`); -} -else if (command.version) { - console.log(`rollup v${rollup.version}`); -} -else { - try { - // eslint-disable-next-line @typescript-eslint/no-require-imports - require('source-map-support').install(); - } - catch { - // do nothing - } - const promise = runRollup(command); - if (command.forceExit) { - promise.then(() => process$1.exit()); - } -} - -exports.getConfigPath = getConfigPath; -exports.loadConfigFromCommand = loadConfigFromCommand; -exports.prettyMilliseconds = prettyMilliseconds; -exports.printTimings = printTimings; -//# sourceMappingURL=rollup.map diff --git a/frontend/node_modules/.bin/rollup b/frontend/node_modules/.bin/rollup new file mode 120000 index 0000000..5939621 --- /dev/null +++ b/frontend/node_modules/.bin/rollup @@ -0,0 +1 @@ +../rollup/dist/bin/rollup \ No newline at end of file diff --git a/frontend/node_modules/.bin/semver b/frontend/node_modules/.bin/semver deleted file mode 100755 index 666034a..0000000 --- a/frontend/node_modules/.bin/semver +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env node -// Standalone semver comparison program. -// Exits successfully and prints matching version(s) if -// any supplied version is valid and passes all tests. - -var argv = process.argv.slice(2) - -var versions = [] - -var range = [] - -var inc = null - -var version = require('../package.json').version - -var loose = false - -var includePrerelease = false - -var coerce = false - -var rtl = false - -var identifier - -var semver = require('../semver') - -var reverse = false - -var options = {} - -main() - -function main () { - if (!argv.length) return help() - while (argv.length) { - var a = argv.shift() - var indexOfEqualSign = a.indexOf('=') - if (indexOfEqualSign !== -1) { - a = a.slice(0, indexOfEqualSign) - argv.unshift(a.slice(indexOfEqualSign + 1)) - } - switch (a) { - case '-rv': case '-rev': case '--rev': case '--reverse': - reverse = true - break - case '-l': case '--loose': - loose = true - break - case '-p': case '--include-prerelease': - includePrerelease = true - break - case '-v': case '--version': - versions.push(argv.shift()) - break - case '-i': case '--inc': case '--increment': - switch (argv[0]) { - case 'major': case 'minor': case 'patch': case 'prerelease': - case 'premajor': case 'preminor': case 'prepatch': - inc = argv.shift() - break - default: - inc = 'patch' - break - } - break - case '--preid': - identifier = argv.shift() - break - case '-r': case '--range': - range.push(argv.shift()) - break - case '-c': case '--coerce': - coerce = true - break - case '--rtl': - rtl = true - break - case '--ltr': - rtl = false - break - case '-h': case '--help': case '-?': - return help() - default: - versions.push(a) - break - } - } - - var options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl } - - versions = versions.map(function (v) { - return coerce ? (semver.coerce(v, options) || { version: v }).version : v - }).filter(function (v) { - return semver.valid(v) - }) - if (!versions.length) return fail() - if (inc && (versions.length !== 1 || range.length)) { return failInc() } - - for (var i = 0, l = range.length; i < l; i++) { - versions = versions.filter(function (v) { - return semver.satisfies(v, range[i], options) - }) - if (!versions.length) return fail() - } - return success(versions) -} - -function failInc () { - console.error('--inc can only be used on a single version with no range') - fail() -} - -function fail () { process.exit(1) } - -function success () { - var compare = reverse ? 'rcompare' : 'compare' - versions.sort(function (a, b) { - return semver[compare](a, b, options) - }).map(function (v) { - return semver.clean(v, options) - }).map(function (v) { - return inc ? semver.inc(v, inc, options, identifier) : v - }).forEach(function (v, i, _) { console.log(v) }) -} - -function help () { - console.log(['SemVer ' + version, - '', - 'A JavaScript implementation of the https://semver.org/ specification', - 'Copyright Isaac Z. Schlueter', - '', - 'Usage: semver [options] [ [...]]', - 'Prints valid versions sorted by SemVer precedence', - '', - 'Options:', - '-r --range ', - ' Print versions that match the specified range.', - '', - '-i --increment []', - ' Increment a version by the specified level. Level can', - ' be one of: major, minor, patch, premajor, preminor,', - " prepatch, or prerelease. Default level is 'patch'.", - ' Only one version may be specified.', - '', - '--preid ', - ' Identifier to be used to prefix premajor, preminor,', - ' prepatch or prerelease version increments.', - '', - '-l --loose', - ' Interpret versions and ranges loosely', - '', - '-p --include-prerelease', - ' Always include prerelease versions in range matching', - '', - '-c --coerce', - ' Coerce a string into SemVer if possible', - ' (does not imply --loose)', - '', - '--rtl', - ' Coerce version strings right to left', - '', - '--ltr', - ' Coerce version strings left to right (default)', - '', - 'Program exits successfully if any valid version satisfies', - 'all supplied ranges, and prints all satisfying versions.', - '', - 'If no satisfying versions are found, then exits failure.', - '', - 'Versions are printed in ascending order, so supplying', - 'multiple versions to the utility will just sort them.' - ].join('\n')) -} diff --git a/frontend/node_modules/.bin/semver b/frontend/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/frontend/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/frontend/node_modules/.bin/update-browserslist-db b/frontend/node_modules/.bin/update-browserslist-db deleted file mode 100755 index 1388e94..0000000 --- a/frontend/node_modules/.bin/update-browserslist-db +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env node - -let { readFileSync } = require('fs') -let { join } = require('path') - -require('./check-npm-version') -let updateDb = require('./') - -const ROOT = __dirname - -function getPackage() { - return JSON.parse(readFileSync(join(ROOT, 'package.json'))) -} - -let args = process.argv.slice(2) - -let USAGE = 'Usage:\n npx update-browserslist-db\n' - -function isArg(arg) { - return args.some(i => i === arg) -} - -function error(msg) { - process.stderr.write('update-browserslist-db: ' + msg + '\n') - process.exit(1) -} - -if (isArg('--help') || isArg('-h')) { - process.stdout.write(getPackage().description + '.\n\n' + USAGE + '\n') -} else if (isArg('--version') || isArg('-v')) { - process.stdout.write('browserslist-lint ' + getPackage().version + '\n') -} else { - try { - updateDb() - } catch (e) { - if (e.name === 'BrowserslistUpdateError') { - error(e.message) - } else { - throw e - } - } -} diff --git a/frontend/node_modules/.bin/update-browserslist-db b/frontend/node_modules/.bin/update-browserslist-db new file mode 120000 index 0000000..b11e16f --- /dev/null +++ b/frontend/node_modules/.bin/update-browserslist-db @@ -0,0 +1 @@ +../update-browserslist-db/cli.js \ No newline at end of file diff --git a/frontend/node_modules/.bin/vite b/frontend/node_modules/.bin/vite deleted file mode 100755 index 23d1139..0000000 --- a/frontend/node_modules/.bin/vite +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env node -import { performance } from 'node:perf_hooks' -import module from 'node:module' - -if (!import.meta.url.includes('node_modules')) { - if (!process.env.DEBUG_DISABLE_SOURCE_MAP) { - // eslint-disable-next-line n/no-unsupported-features/node-builtins -- only used in dev - process.setSourceMapsEnabled(true) - } - - process.on('unhandledRejection', (err) => { - throw new Error('UNHANDLED PROMISE REJECTION', { cause: err }) - }) -} - -global.__vite_start_time = performance.now() - -// check debug mode first before requiring the CLI. -const debugIndex = process.argv.findIndex((arg) => /^(?:-d|--debug)$/.test(arg)) -const filterIndex = process.argv.findIndex((arg) => - /^(?:-f|--filter)$/.test(arg), -) -const profileIndex = process.argv.indexOf('--profile') - -if (debugIndex > 0) { - let value = process.argv[debugIndex + 1] - if (!value || value.startsWith('-')) { - value = 'vite:*' - } else { - // support debugging multiple flags with comma-separated list - value = value - .split(',') - .map((v) => `vite:${v}`) - .join(',') - } - process.env.DEBUG = `${ - process.env.DEBUG ? process.env.DEBUG + ',' : '' - }${value}` - - if (filterIndex > 0) { - const filter = process.argv[filterIndex + 1] - if (filter && !filter.startsWith('-')) { - process.env.VITE_DEBUG_FILTER = filter - } - } -} - -function start() { - try { - // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.8.0+ and only called if it exists - module.enableCompileCache?.() - // flush the cache after 10s because the cache is not flushed until process end - // for dev server, the cache is never flushed unless manually flushed because the process.exit is called - // also flushing the cache in SIGINT handler seems to cause the process to hang - setTimeout(() => { - try { - // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.12.0+ and only called if it exists - module.flushCompileCache?.() - } catch {} - }, 10 * 1000).unref() - } catch {} - return import('../dist/node/cli.js') -} - -if (profileIndex > 0) { - process.argv.splice(profileIndex, 1) - const next = process.argv[profileIndex] - if (next && !next.startsWith('-')) { - process.argv.splice(profileIndex, 1) - } - const inspector = await import('node:inspector').then((r) => r.default) - const session = (global.__vite_profile_session = new inspector.Session()) - session.connect() - session.post('Profiler.enable', () => { - session.post('Profiler.start', start) - }) -} else { - start() -} diff --git a/frontend/node_modules/.bin/vite b/frontend/node_modules/.bin/vite new file mode 120000 index 0000000..6d1e3be --- /dev/null +++ b/frontend/node_modules/.bin/vite @@ -0,0 +1 @@ +../vite/bin/vite.js \ No newline at end of file diff --git a/frontend/node_modules/.package-lock.json b/frontend/node_modules/.package-lock.json index e09153c..fd79be0 100644 --- a/frontend/node_modules/.package-lock.json +++ b/frontend/node_modules/.package-lock.json @@ -1723,7 +1723,6 @@ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", "dev": true, "hasInstallScript": true, - "ideallyInert": true, "license": "MIT", "optional": true, "os": [ diff --git a/frontend/node_modules/.vite/deps/_metadata.json b/frontend/node_modules/.vite/deps/_metadata.json index fef7e5a..158a2fd 100644 --- a/frontend/node_modules/.vite/deps/_metadata.json +++ b/frontend/node_modules/.vite/deps/_metadata.json @@ -1,43 +1,43 @@ { - "hash": "e7b50dfd", - "configHash": "a071e958", - "lockfileHash": "275b9368", - "browserHash": "577bd8b4", + "hash": "564d4159", + "configHash": "05f98eb2", + "lockfileHash": "2ac3976d", + "browserHash": "d160b50d", "optimized": { "react": { "src": "../../react/index.js", "file": "react.js", - "fileHash": "bb692064", + "fileHash": "c51949fb", "needsInterop": true }, "react-dom/client": { "src": "../../react-dom/client.js", "file": "react-dom_client.js", - "fileHash": "b3d7cc7b", + "fileHash": "66f2cda3", "needsInterop": true }, "react-markdown": { "src": "../../react-markdown/index.js", "file": "react-markdown.js", - "fileHash": "ecce3e61", + "fileHash": "2f1a1862", "needsInterop": false }, "react-quill": { "src": "../../react-quill/lib/index.js", "file": "react-quill.js", - "fileHash": "94cdf64a", + "fileHash": "68a5df8d", "needsInterop": true }, "react-router-dom": { "src": "../../react-router-dom/dist/index.mjs", "file": "react-router-dom.js", - "fileHash": "243d7931", + "fileHash": "39071eab", "needsInterop": false }, "rehype-raw": { "src": "../../rehype-raw/index.js", "file": "rehype-raw.js", - "fileHash": "32293b6b", + "fileHash": "3038c436", "needsInterop": false } }, diff --git a/frontend/node_modules/fsevents/LICENSE b/frontend/node_modules/fsevents/LICENSE new file mode 100644 index 0000000..5d70441 --- /dev/null +++ b/frontend/node_modules/fsevents/LICENSE @@ -0,0 +1,22 @@ +MIT License +----------- + +Copyright (C) 2010-2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/frontend/node_modules/fsevents/README.md b/frontend/node_modules/fsevents/README.md new file mode 100644 index 0000000..50373a0 --- /dev/null +++ b/frontend/node_modules/fsevents/README.md @@ -0,0 +1,89 @@ +# fsevents + +Native access to MacOS FSEvents in [Node.js](https://nodejs.org/) + +The FSEvents API in MacOS allows applications to register for notifications of +changes to a given directory tree. It is a very fast and lightweight alternative +to kqueue. + +This is a low-level library. For a cross-platform file watching module that +uses fsevents, check out [Chokidar](https://github.com/paulmillr/chokidar). + +## Usage + +```sh +npm install fsevents +``` + +Supports only **Node.js v8.16 and higher**. + +```js +const fsevents = require('fsevents'); + +// To start observation +const stop = fsevents.watch(__dirname, (path, flags, id) => { + const info = fsevents.getInfo(path, flags); +}); + +// To end observation +stop(); +``` + +> **Important note:** The API behaviour is slightly different from typical JS APIs. The `stop` function **must** be +> retrieved and stored somewhere, even if you don't plan to stop the watcher. If you forget it, the garbage collector +> will eventually kick in, the watcher will be unregistered, and your callbacks won't be called anymore. + +The callback passed as the second parameter to `.watch` get's called whenever the operating system detects a +a change in the file system. It takes three arguments: + +###### `fsevents.watch(dirname: string, (path: string, flags: number, id: string) => void): () => Promise` + + * `path: string` - the item in the filesystem that have been changed + * `flags: number` - a numeric value describing what the change was + * `id: string` - an unique-id identifying this specific event + + Returns closer callback which when called returns a Promise resolving when the watcher process has been shut down. + +###### `fsevents.getInfo(path: string, flags: number, id: string): FsEventInfo` + +The `getInfo` function takes the `path`, `flags` and `id` arguments and converts those parameters into a structure +that is easier to digest to determine what the change was. + +The `FsEventsInfo` has the following shape: + +```js +/** + * @typedef {'created'|'modified'|'deleted'|'moved'|'root-changed'|'cloned'|'unknown'} FsEventsEvent + * @typedef {'file'|'directory'|'symlink'} FsEventsType + */ +{ + "event": "created", // {FsEventsEvent} + "path": "file.txt", + "type": "file", // {FsEventsType} + "changes": { + "inode": true, // Had iNode Meta-Information changed + "finder": false, // Had Finder Meta-Data changed + "access": false, // Had access permissions changed + "xattrs": false // Had xAttributes changed + }, + "flags": 0x100000000 +} +``` + +## Changelog + +- v2.3 supports Apple Silicon ARM CPUs +- v2 supports node 8.16+ and reduces package size massively +- v1.2.8 supports node 6+ +- v1.2.7 supports node 4+ + +## Troubleshooting + +- I'm getting `EBADPLATFORM` `Unsupported platform for fsevents` error. +- It's fine, nothing is broken. fsevents is macos-only. Other platforms are skipped. If you want to hide this warning, report a bug to NPM bugtracker asking them to hide ebadplatform warnings by default. + +## License + +The MIT License Copyright (C) 2010-2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller — see LICENSE file. + +Visit our [GitHub page](https://github.com/fsevents/fsevents) and [NPM Page](https://npmjs.org/package/fsevents) diff --git a/frontend/node_modules/fsevents/fsevents.d.ts b/frontend/node_modules/fsevents/fsevents.d.ts new file mode 100644 index 0000000..2723c04 --- /dev/null +++ b/frontend/node_modules/fsevents/fsevents.d.ts @@ -0,0 +1,46 @@ +declare type Event = "created" | "cloned" | "modified" | "deleted" | "moved" | "root-changed" | "unknown"; +declare type Type = "file" | "directory" | "symlink"; +declare type FileChanges = { + inode: boolean; + finder: boolean; + access: boolean; + xattrs: boolean; +}; +declare type Info = { + event: Event; + path: string; + type: Type; + changes: FileChanges; + flags: number; +}; +declare type WatchHandler = (path: string, flags: number, id: string) => void; +export declare function watch(path: string, handler: WatchHandler): () => Promise; +export declare function watch(path: string, since: number, handler: WatchHandler): () => Promise; +export declare function getInfo(path: string, flags: number): Info; +export declare const constants: { + None: 0x00000000; + MustScanSubDirs: 0x00000001; + UserDropped: 0x00000002; + KernelDropped: 0x00000004; + EventIdsWrapped: 0x00000008; + HistoryDone: 0x00000010; + RootChanged: 0x00000020; + Mount: 0x00000040; + Unmount: 0x00000080; + ItemCreated: 0x00000100; + ItemRemoved: 0x00000200; + ItemInodeMetaMod: 0x00000400; + ItemRenamed: 0x00000800; + ItemModified: 0x00001000; + ItemFinderInfoMod: 0x00002000; + ItemChangeOwner: 0x00004000; + ItemXattrMod: 0x00008000; + ItemIsFile: 0x00010000; + ItemIsDir: 0x00020000; + ItemIsSymlink: 0x00040000; + ItemIsHardlink: 0x00100000; + ItemIsLastHardlink: 0x00200000; + OwnEvent: 0x00080000; + ItemCloned: 0x00400000; +}; +export {}; diff --git a/frontend/node_modules/fsevents/fsevents.js b/frontend/node_modules/fsevents/fsevents.js new file mode 100644 index 0000000..198da98 --- /dev/null +++ b/frontend/node_modules/fsevents/fsevents.js @@ -0,0 +1,83 @@ +/* + ** © 2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller + ** Licensed under MIT License. + */ + +/* jshint node:true */ +"use strict"; + +if (process.platform !== "darwin") { + throw new Error(`Module 'fsevents' is not compatible with platform '${process.platform}'`); +} + +const Native = require("./fsevents.node"); +const events = Native.constants; + +function watch(path, since, handler) { + if (typeof path !== "string") { + throw new TypeError(`fsevents argument 1 must be a string and not a ${typeof path}`); + } + if ("function" === typeof since && "undefined" === typeof handler) { + handler = since; + since = Native.flags.SinceNow; + } + if (typeof since !== "number") { + throw new TypeError(`fsevents argument 2 must be a number and not a ${typeof since}`); + } + if (typeof handler !== "function") { + throw new TypeError(`fsevents argument 3 must be a function and not a ${typeof handler}`); + } + + let instance = Native.start(Native.global, path, since, handler); + if (!instance) throw new Error(`could not watch: ${path}`); + return () => { + const result = instance ? Promise.resolve(instance).then(Native.stop) : Promise.resolve(undefined); + instance = undefined; + return result; + }; +} + +function getInfo(path, flags) { + return { + path, + flags, + event: getEventType(flags), + type: getFileType(flags), + changes: getFileChanges(flags), + }; +} + +function getFileType(flags) { + if (events.ItemIsFile & flags) return "file"; + if (events.ItemIsDir & flags) return "directory"; + if (events.MustScanSubDirs & flags) return "directory"; + if (events.ItemIsSymlink & flags) return "symlink"; +} +function anyIsTrue(obj) { + for (let key in obj) { + if (obj[key]) return true; + } + return false; +} +function getEventType(flags) { + if (events.ItemRemoved & flags) return "deleted"; + if (events.ItemRenamed & flags) return "moved"; + if (events.ItemCreated & flags) return "created"; + if (events.ItemModified & flags) return "modified"; + if (events.RootChanged & flags) return "root-changed"; + if (events.ItemCloned & flags) return "cloned"; + if (anyIsTrue(flags)) return "modified"; + return "unknown"; +} +function getFileChanges(flags) { + return { + inode: !!(events.ItemInodeMetaMod & flags), + finder: !!(events.ItemFinderInfoMod & flags), + access: !!(events.ItemChangeOwner & flags), + xattrs: !!(events.ItemXattrMod & flags), + }; +} + +exports.watch = watch; +exports.getInfo = getInfo; +exports.constants = events; diff --git a/frontend/node_modules/fsevents/fsevents.node b/frontend/node_modules/fsevents/fsevents.node new file mode 100755 index 0000000..1cc3345 Binary files /dev/null and b/frontend/node_modules/fsevents/fsevents.node differ diff --git a/frontend/node_modules/fsevents/package.json b/frontend/node_modules/fsevents/package.json new file mode 100644 index 0000000..5d0ee15 --- /dev/null +++ b/frontend/node_modules/fsevents/package.json @@ -0,0 +1,62 @@ +{ + "name": "fsevents", + "version": "2.3.3", + "description": "Native Access to MacOS FSEvents", + "main": "fsevents.js", + "types": "fsevents.d.ts", + "os": [ + "darwin" + ], + "files": [ + "fsevents.d.ts", + "fsevents.js", + "fsevents.node" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + }, + "scripts": { + "clean": "node-gyp clean && rm -f fsevents.node", + "build": "node-gyp clean && rm -f fsevents.node && node-gyp rebuild && node-gyp clean", + "test": "/bin/bash ./test.sh 2>/dev/null", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "https://github.com/fsevents/fsevents.git" + }, + "keywords": [ + "fsevents", + "mac" + ], + "contributors": [ + { + "name": "Philipp Dunkel", + "email": "pip@pipobscure.com" + }, + { + "name": "Ben Noordhuis", + "email": "info@bnoordhuis.nl" + }, + { + "name": "Elan Shankar", + "email": "elan.shanker@gmail.com" + }, + { + "name": "Miroslav Bajtoš", + "email": "mbajtoss@gmail.com" + }, + { + "name": "Paul Miller", + "url": "https://paulmillr.com" + } + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/fsevents/fsevents/issues" + }, + "homepage": "https://github.com/fsevents/fsevents", + "devDependencies": { + "node-gyp": "^9.4.0" + } +}