diff --git a/README.md b/README.md index 22baf54f..e4cbb9fc 100644 --- a/README.md +++ b/README.md @@ -50,12 +50,11 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} USERNAME: ${{ github.repository_owner }} - name: Commit & Push - run: | - git config user.name github-actions - git config user.email github-actions@github.com - git add -A . - git commit -m "generated" - git push + run: | + git config user.name github-actions + git config user.email github-actions@github.com + git add -A . + git diff --staged --exit-code || (git commit -m "generated" && git push) ``` Note: If you also want to include the private repository, register the "personal access token" in the repository and set it to GITHUB_TOKEN specified in the workflow file. @@ -67,6 +66,8 @@ This will add the action to the repository. * `GITHUB_TOKEN` : (required) access token * `USERNAME` : (required) target user name (or specify with an argument). * `MAX_REPOS` : (optional) max repositories, default 100 - since ver. 0.2.0 +* `MAX_LANGUAGES` : (optional) maximum number of languages to display on pie chart, default 5. +* `IGNORE_LANGUAGES` : (optional) comma delimited list of languages to ignore. * `SETTING_JSON` : (optional) settings json file path. See `sample-settings/*.json` and `src/type.ts` in `yoshi389111/github-profile-3d-contrib` repository for details. - since ver. 0.6.0 ### step 3. Manually launch the action diff --git a/dist/index.js b/dist/index.js index 33272aff..9da365b3 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,2293 +1,689 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 34734: -/***/ ((__unused_webpack_module, exports) => { +/***/ 87351: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.aggregateUserInfo = void 0; -const OTHER_COLOR = '#444444'; -const toNumberContributionLevel = (level) => { - switch (level) { - case 'NONE': - return 0; - case 'FIRST_QUARTILE': - return 1; - case 'SECOND_QUARTILE': - return 2; - case 'THIRD_QUARTILE': - return 3; - case 'FOURTH_QUARTILE': - return 4; - } -}; -const compare = (num1, num2) => { - if (num1 < num2) { - return -1; - } - else if (num1 > num2) { - return 1; - } - else { - return 0; - } +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; }; -const aggregateUserInfo = (response) => { - if (!response.data) { - if (response.errors && response.errors.length) { - throw new Error(response.errors[0].message); - } - else { - throw new Error('JSON\n' + JSON.stringify(response, null, 2)); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(5278); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; } + this.command = command; + this.properties = properties; + this.message = message; } - const user = response.data.user; - const calendar = user.contributionsCollection.contributionCalendar.weeks - .flatMap((week) => week.contributionDays) - .map((week) => ({ - contributionCount: week.contributionCount, - contributionLevel: toNumberContributionLevel(week.contributionLevel), - date: new Date(week.date), - })); - const contributesLanguage = {}; - user.contributionsCollection.commitContributionsByRepository - .filter((repo) => repo.repository.primaryLanguage) - .forEach((repo) => { - var _a, _b; - const language = ((_a = repo.repository.primaryLanguage) === null || _a === void 0 ? void 0 : _a.name) || ''; - const color = ((_b = repo.repository.primaryLanguage) === null || _b === void 0 ? void 0 : _b.color) || OTHER_COLOR; - const contributions = repo.contributions.totalCount; - const info = contributesLanguage[language]; - if (info) { - info.contributions += contributions; - } - else { - contributesLanguage[language] = { - language: language, - color: color, - contributions: contributions, - }; + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } } - }); - const languages = Object.values(contributesLanguage).sort((obj1, obj2) => -compare(obj1.contributions, obj2.contributions)); - const totalForkCount = user.repositories.nodes - .map((node) => node.forkCount) - .reduce((num1, num2) => num1 + num2, 0); - const totalStargazerCount = user.repositories.nodes - .map((node) => node.stargazerCount) - .reduce((num1, num2) => num1 + num2, 0); - const userInfo = { - isHalloween: user.contributionsCollection.contributionCalendar.isHalloween, - contributionCalendar: calendar, - contributesLanguage: languages, - totalContributions: user.contributionsCollection.contributionCalendar - .totalContributions, - totalCommitContributions: user.contributionsCollection.totalCommitContributions, - totalIssueContributions: user.contributionsCollection.totalIssueContributions, - totalPullRequestContributions: user.contributionsCollection.totalPullRequestContributions, - totalPullRequestReviewContributions: user.contributionsCollection.totalPullRequestReviewContributions, - totalRepositoryContributions: user.contributionsCollection.totalRepositoryContributions, - totalForkCount: totalForkCount, - totalStargazerCount: totalStargazerCount, - }; - return userInfo; -}; -exports.aggregateUserInfo = aggregateUserInfo; -//# sourceMappingURL=aggregate-user-info.js.map + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +function escapeData(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map /***/ }), -/***/ 67007: -/***/ ((__unused_webpack_module, exports) => { +/***/ 42186: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GitBlockSettings = exports.NightRainbowSettings = exports.NightGreenSettings = exports.NightViewSettings = exports.SouthSeasonSettings = exports.NorthSeasonSettings = exports.HalloweenSettings = exports.NormalSettings = void 0; -exports.NormalSettings = { - type: 'normal', - backgroundColor: '#ffffff', - foregroundColor: '#00000f', - strongColor: '#111133', - weakColor: 'gray', - radarColor: '#47a042', - contribColors: ['#efefef', '#d8e887', '#8cc569', '#47a042', '#1d6a23'], -}; -exports.HalloweenSettings = { - type: 'normal', - backgroundColor: '#ffffff', - foregroundColor: '#00000f', - strongColor: '#111133', - weakColor: 'gray', - radarColor: '#47a042', - contribColors: ['#efefef', '#ffed4a', '#ffc402', '#fe9400', '#fa6100'], -}; -// Northern hemisphere -exports.NorthSeasonSettings = { - type: 'season', - backgroundColor: '#ffffff', - foregroundColor: '#00000f', - strongColor: '#111133', - weakColor: 'gray', - radarColor: '#47a042', - contribColors1: ['#efefef', '#ffe7ff', '#edaeda', '#e492ca', '#ba7aad'], - contribColors2: ['#efefef', '#d8e887', '#8cc569', '#47a042', '#1d6a23'], - contribColors3: ['#efefef', '#ffed4a', '#ffc402', '#fe9400', '#fa6100'], - contribColors4: ['#efefef', '#999999', '#cccccc', '#dddddd', '#eeeeee'], // winter -}; -// Southern hemisphere -exports.SouthSeasonSettings = { - type: 'season', - backgroundColor: '#ffffff', - foregroundColor: '#00000f', - strongColor: '#111133', - weakColor: 'gray', - radarColor: '#47a042', - contribColors1: ['#efefef', '#ffed4a', '#ffc402', '#fe9400', '#fa6100'], - contribColors2: ['#efefef', '#999999', '#cccccc', '#dddddd', '#eeeeee'], - contribColors3: ['#efefef', '#ffe7ff', '#edaeda', '#e492ca', '#ba7aad'], - contribColors4: ['#efefef', '#d8e887', '#8cc569', '#47a042', '#1d6a23'], // summer -}; -exports.NightViewSettings = { - type: 'normal', - backgroundColor: '#00000f', - foregroundColor: '#eeeeff', - strongColor: 'rgb(255,200,55)', - weakColor: '#aaaaaa', - radarColor: 'rgb(255,200,55)', - contribColors: [ - 'rgb(25,60,130)', - 'rgb(25,90,210)', - 'rgb(25,120,220)', - 'rgb(25,150,230)', - 'rgb(25,165,240)', - ], -}; -exports.NightGreenSettings = { - type: 'normal', - backgroundColor: '#00000f', - foregroundColor: '#eeeeff', - strongColor: 'rgb(255,200,55)', - weakColor: '#aaaaaa', - radarColor: '#47a042', - contribColors: ['#444444', '#1B7D28', '#24A736', '#2DD143', '#57DA69'], -}; -exports.NightRainbowSettings = { - type: 'rainbow', - backgroundColor: '#00000f', - foregroundColor: '#eeeeff', - strongColor: 'rgb(255,200,55)', - weakColor: '#aaaaaa', - radarColor: 'rgb(255,200,55)', - saturation: '50%', - contribLightness: ['20%', '30%', '35%', '40%', '50%'], - duration: '10s', - hueRatio: -7, +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; -exports.GitBlockSettings = { - type: 'bitmap', - backgroundColor: '#ffffff', - foregroundColor: '#00000f', - strongColor: '#111133', - weakColor: 'gray', - radarColor: '#47a042', - contribPatterns: [ - { - top: { - backgroundColor: '#f8f8f8', - foregroundColor: '#aaaaaa', - width: 32, - bitmap: [ - 0, - 0, - 29360576, - 103810608, - 168299016, - 302518792, - 285479172, - 293867908, - 314839748, - 225971576, - 178784936, - 122685264, - 31457760, - 0, - 0, - 0, - ], - }, - left: { - width: 32, - bitmap: [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2863311530, - ], - }, - right: { - width: 32, - bitmap: [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2863311530, - ], - }, - }, - { - top: { - backgroundColor: 'hsl(125, 52%, 50%)', - foregroundColor: 'hsl(125, 52%, 10%)', - width: 32, - bitmap: [ - 0, - 0, - 29360576, - 103810608, - 168299016, - 302518792, - 285479172, - 293867908, - 314839748, - 225971576, - 178784936, - 122685264, - 31457760, - 0, - 0, - 0, - ], - }, - left: { - width: 32, - bitmap: [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2863311530, - ], - }, - right: { - width: 32, - bitmap: [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2863311530, - ], - }, - }, - { - top: { - backgroundColor: 'hsl(242, 100%, 65%)', - foregroundColor: 'hsl(242, 100%, 16%)', - width: 32, - bitmap: [ - 0, - 0, - 29360576, - 103810608, - 168299016, - 302518792, - 285479172, - 293867908, - 314839748, - 225971576, - 178784936, - 122685264, - 31457760, - 0, - 0, - 0, - ], - }, - left: { - width: 32, - bitmap: [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2863311530, - ], - }, - right: { - width: 32, - bitmap: [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2863311530, - ], - }, - }, - { - top: { - backgroundColor: 'hsl(48, 100%, 50%)', - foregroundColor: 'hsl(48, 100%, 15%)', - width: 32, - bitmap: [ - 0, - 0, - 29360576, - 103810608, - 168299016, - 302518792, - 285479172, - 293867908, - 314839748, - 225971576, - 178784936, - 122685264, - 31457760, - 0, - 0, - 0, - ], - }, - left: { - width: 32, - bitmap: [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2863311530, - ], - }, - right: { - width: 32, - bitmap: [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2863311530, - ], - }, - }, - { - top: { - backgroundColor: 'hsl(350, 100%, 50%)', - foregroundColor: 'hsl(350, 100%, 15%)', - width: 32, - bitmap: [ - 0, - 0, - 29360576, - 103810608, - 168299016, - 302518792, - 285479172, - 293867908, - 314839748, - 225971576, - 178784936, - 122685264, - 31457760, - 0, - 0, - 0, - ], - }, - left: { - width: 32, - bitmap: [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2863311530, - ], - }, - right: { - width: 32, - bitmap: [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2863311530, - ], - }, - }, - ], +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; }; -//# sourceMappingURL=color-template.js.map +Object.defineProperty(exports, "__esModule", ({ value: true })); +const command_1 = __nccwpck_require__(87351); +const file_command_1 = __nccwpck_require__(717); +const utils_1 = __nccwpck_require__(5278); +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = utils_1.toCommandValue(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + const delimiter = '_GitHubActionsFileCommandDelimeter_'; + const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; + file_command_1.issueCommand('ENV', commandValue); + } + else { + command_1.issueCommand('set-env', { name }, convertedVal); + } +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + command_1.issueCommand('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + file_command_1.issueCommand('PATH', inputPath); + } + else { + command_1.issueCommand('add-path', {}, inputPath); + } + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. The value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + return val.trim(); +} +exports.getInput = getInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + process.stdout.write(os.EOL); + command_1.issueCommand('set-output', { name }, value); +} +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + command_1.issueCommand('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + */ +function error(message) { + command_1.issue('error', message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds an warning issue + * @param message warning issue message. Errors will be converted to string via toString() + */ +function warning(message) { + command_1.issue('warning', message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + command_1.issue('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + command_1.issue('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + command_1.issueCommand('save-state', { name }, value); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +//# sourceMappingURL=core.js.map /***/ }), -/***/ 78739: +/***/ 717: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); +// For internal use, subject to change. var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.create3DContrib = exports.addDefines = void 0; -const d3 = __importStar(__nccwpck_require__(45203)); -const util = __importStar(__nccwpck_require__(21458)); -const ANGLE = 30; -const DARKER_RIGHT = 1; -const DARKER_LEFT = 0.5; -const DARKER_TOP = 0; -const diffDate = (beforeDate, afterDate) => Math.floor((afterDate - beforeDate) / (24 * 60 * 60 * 1000)); -const createGradation = (dayOfMonth, color1, color2) => { - let ratio; - if (dayOfMonth <= 7) { - ratio = 0.2; - } - else if (dayOfMonth <= 14) { - ratio = 0.4; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fs = __importStar(__nccwpck_require__(57147)); +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(5278); +function issueCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); } - else if (dayOfMonth <= 21) { - ratio = 0.6; + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); } - else if (dayOfMonth <= 28) { - ratio = 0.8; + fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + encoding: 'utf8' + }); +} +exports.issueCommand = issueCommand; +//# sourceMappingURL=file-command.js.map + +/***/ }), + +/***/ 5278: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; } - else { - return color2; + else if (typeof input === 'string' || input instanceof String) { + return input; } - const color = d3.interpolate(color1, color2); - return color(ratio); + return JSON.stringify(input); +} +exports.toCommandValue = toCommandValue; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 75696: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const atob = __nccwpck_require__(84732); +const btoa = __nccwpck_require__(50012); + +module.exports = { + atob, + btoa }; -const decideSeasonColor = (contributionLevel, settings, date) => { - const sunday = new Date(date.getTime()); - sunday.setDate(sunday.getDate() - sunday.getDay()); - const month = sunday.getUTCMonth(); - const dayOfMonth = sunday.getUTCDate(); - switch (month + 1) { - case 9: - // summer -> autumn - return createGradation(dayOfMonth, settings.contribColors2[contributionLevel], settings.contribColors3[contributionLevel]); - case 10: - case 11: - // autumn - return settings.contribColors3[contributionLevel]; - case 12: - // autumn -> winter - return createGradation(dayOfMonth, settings.contribColors3[contributionLevel], settings.contribColors4[contributionLevel]); - case 1: - case 2: - // winter - return settings.contribColors4[contributionLevel]; - case 3: - // winter -> spring - return createGradation(dayOfMonth, settings.contribColors4[contributionLevel], settings.contribColors1[contributionLevel]); - case 4: - case 5: - // spring - return settings.contribColors1[contributionLevel]; - case 6: - // spring -> summer - return createGradation(dayOfMonth, settings.contribColors1[contributionLevel], settings.contribColors2[contributionLevel]); - case 7: - case 8: - default: - // summer - return settings.contribColors2[contributionLevel]; + + +/***/ }), + +/***/ 84732: +/***/ ((module) => { + +"use strict"; + + +/** + * Implementation of atob() according to the HTML and Infra specs, except that + * instead of throwing INVALID_CHARACTER_ERR we return null. + */ +function atob(data) { + // Web IDL requires DOMStrings to just be converted using ECMAScript + // ToString, which in our case amounts to using a template literal. + data = `${data}`; + // "Remove all ASCII whitespace from data." + data = data.replace(/[ \t\n\f\r]/g, ""); + // "If data's length divides by 4 leaving no remainder, then: if data ends + // with one or two U+003D (=) code points, then remove them from data." + if (data.length % 4 === 0) { + data = data.replace(/==?$/, ""); + } + // "If data's length divides by 4 leaving a remainder of 1, then return + // failure." + // + // "If data contains a code point that is not one of + // + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // + // then return failure." + if (data.length % 4 === 1 || /[^+/0-9A-Za-z]/.test(data)) { + return null; + } + // "Let output be an empty byte sequence." + let output = ""; + // "Let buffer be an empty buffer that can have bits appended to it." + // + // We append bits via left-shift and or. accumulatedBits is used to track + // when we've gotten to 24 bits. + let buffer = 0; + let accumulatedBits = 0; + // "Let position be a position variable for data, initially pointing at the + // start of data." + // + // "While position does not point past the end of data:" + for (let i = 0; i < data.length; i++) { + // "Find the code point pointed to by position in the second column of + // Table 1: The Base 64 Alphabet of RFC 4648. Let n be the number given in + // the first cell of the same row. + // + // "Append to buffer the six bits corresponding to n, most significant bit + // first." + // + // atobLookup() implements the table from RFC 4648. + buffer <<= 6; + buffer |= atobLookup(data[i]); + accumulatedBits += 6; + // "If buffer has accumulated 24 bits, interpret them as three 8-bit + // big-endian numbers. Append three bytes with values equal to those + // numbers to output, in the same order, and then empty buffer." + if (accumulatedBits === 24) { + output += String.fromCharCode((buffer & 0xff0000) >> 16); + output += String.fromCharCode((buffer & 0xff00) >> 8); + output += String.fromCharCode(buffer & 0xff); + buffer = accumulatedBits = 0; } -}; -const addNormalColor = (path, contributionLevel, settings, darker) => { - const color = settings.contribColors[contributionLevel]; - path.attr('fill', d3.rgb(color).darker(darker).toString()); -}; -const addSeasonColor = (path, contributionLevel, settings, darker, date) => { - const color = decideSeasonColor(contributionLevel, settings, date); - path.attr('fill', d3.rgb(color).darker(darker).toString()); -}; -const addRainbowColor = (path, contributionLevel, settings, darker, week) => { - const offsetHue = week * settings.hueRatio; - const saturation = settings.saturation; - const lightness = settings.contribLightness[contributionLevel]; - const values = [...Array(7)] - .map((_, i) => (i * 60 + offsetHue) % 360) - .map((hue) => `hsl(${hue},${saturation},${lightness})`) - .map((c) => d3.rgb(c).darker(darker).toString()) - .join(';'); - path.append('animate') - .attr('attributeName', 'fill') - .attr('values', values) - .attr('dur', settings.duration) - .attr('repeatCount', 'indefinite'); -}; -const addBitmapPattern = (path, contributionLevel, panel) => { - path.attr('fill', `url(#pattern_${contributionLevel}_${panel})`); -}; -const atan = (value) => (Math.atan(value) * 360) / 2 / Math.PI; -const addPatternForBitmap = (defs, panelPattern, contributionLevel, panel, backgroundColor, foregroundColor) => { - const width = Math.max(1, panelPattern.width); - const height = Math.max(1, panelPattern.bitmap.length); - const pattern = defs - .append('pattern') - .attr('id', `pattern_${contributionLevel}_${panel}`) - .attr('x', 0) - .attr('y', 0) - .attr('width', width) - .attr('height', height) - .attr('patternUnits', 'userSpaceOnUse'); - pattern - .append('rect') - .attr('x', 0) - .attr('y', 0) - .attr('width', width) - .attr('height', height) - .attr('fill', backgroundColor); - const path = d3.path(); - for (const [y, bitmapValue] of panelPattern.bitmap.entries()) { - const bitmap = typeof bitmapValue === 'string' - ? parseInt(bitmapValue, 16) - : bitmapValue; - for (let x = 0; x < width; x++) { - if ((bitmap & (1 << (width - x - 1))) !== 0) { - path.rect(x, y, 1, 1); - } - } - } - pattern - .append('path') - .attr('stroke', 'none') - .attr('fill', foregroundColor) - .attr('d', path.toString()); -}; -const addDefines = (svg, settings) => { - if (settings.type === 'bitmap') { - const defs = svg.append('defs'); - for (const [contribLevel, info] of settings.contribPatterns.entries()) { - addPatternForBitmap(defs, info.top, contribLevel, 'top', info.top.backgroundColor, info.top.foregroundColor); - addPatternForBitmap(defs, info.left, contribLevel, 'left', info.left.backgroundColor || - d3 - .rgb(info.top.backgroundColor) - .darker(DARKER_LEFT) - .toString(), info.left.foregroundColor || - d3 - .rgb(info.top.foregroundColor) - .darker(DARKER_LEFT) - .toString()); - addPatternForBitmap(defs, info.right, contribLevel, 'right', info.right.backgroundColor || - d3 - .rgb(info.top.backgroundColor) - .darker(DARKER_RIGHT) - .toString(), info.right.foregroundColor || - d3 - .rgb(info.top.foregroundColor) - .darker(DARKER_RIGHT) - .toString()); - } - } -}; -exports.addDefines = addDefines; -const create3DContrib = (svg, userInfo, x, y, width, height, settings, isForcedAnimation = false) => { - if (userInfo.contributionCalendar.length === 0) { - return; - } - const startTime = userInfo.contributionCalendar[0].date.getTime(); - const dx = width / 64; - const dy = dx * Math.tan(ANGLE * ((2 * Math.PI) / 360)); - const weekcount = Math.ceil(userInfo.contributionCalendar.length / 7.0); - const dxx = dx * 0.9; - const dyy = dy * 0.9; - const offsetX = dx * 7; - const offsetY = height - (weekcount + 7) * dy; - const group = svg.append('g'); - userInfo.contributionCalendar.forEach((cal) => { - const dayOfWeek = cal.date.getUTCDay(); // sun = 0, mon = 1, ... - const week = Math.floor(diffDate(startTime, cal.date.getTime()) / 7); - const baseX = offsetX + (week - dayOfWeek) * dx; - const baseY = offsetY + (week + dayOfWeek) * dy; - const calHeight = Math.log10(cal.contributionCount / 20 + 1) * 144 + 3; - const contribLevel = cal.contributionLevel; - const isAnimate = settings.growingAnimation || isForcedAnimation; - const bar = group - .append('g') - .attr('transform', `translate(${util.toFixed(baseX)} ${util.toFixed(baseY - calHeight)})`); - if (isAnimate && contribLevel !== 0) { - bar.append('animateTransform') - .attr('attributeName', 'transform') - .attr('type', 'translate') - .attr('values', `${util.toFixed(baseX)} ${util.toFixed(baseY - 3)};${util.toFixed(baseX)} ${util.toFixed(baseY - calHeight)}`) - .attr('dur', '3s') - .attr('repeatCount', '1'); - } - const widthTop = settings.type === 'bitmap' - ? Math.max(1, settings.contribPatterns[contribLevel].top.width) - : dxx; - const topPanel = bar - .append('rect') - .attr('stroke', 'none') - .attr('x', 0) - .attr('y', 0) - .attr('width', util.toFixed(widthTop)) - .attr('height', util.toFixed(widthTop)) - .attr('transform', `skewY(${-ANGLE}) skewX(${util.toFixed(atan(dxx / 2 / dyy))}) scale(${util.toFixed(dxx / widthTop)} ${util.toFixed((2 * dyy) / widthTop)})`); - if (settings.type === 'normal') { - addNormalColor(topPanel, contribLevel, settings, DARKER_TOP); - } - else if (settings.type === 'season') { - addSeasonColor(topPanel, contribLevel, settings, DARKER_TOP, cal.date); - } - else if (settings.type === 'rainbow') { - addRainbowColor(topPanel, contribLevel, settings, DARKER_TOP, week); - } - else if (settings.type === 'bitmap') { - addBitmapPattern(topPanel, contribLevel, 'top'); - } - const widthLeft = settings.type === 'bitmap' - ? Math.max(1, settings.contribPatterns[contribLevel].left.width) - : dxx; - const scaleLeft = Math.sqrt(dxx ** 2 + dyy ** 2) / widthLeft; - const heightLeft = calHeight / scaleLeft; - const leftPanel = bar - .append('rect') - .attr('stroke', 'none') - .attr('x', 0) - .attr('y', 0) - .attr('width', util.toFixed(widthLeft)) - .attr('height', util.toFixed(heightLeft)) - .attr('transform', `skewY(${ANGLE}) scale(${util.toFixed(dxx / widthLeft)} ${util.toFixed(scaleLeft)})`); - if (settings.type === 'normal') { - addNormalColor(leftPanel, contribLevel, settings, DARKER_LEFT); - } - else if (settings.type === 'season') { - addSeasonColor(leftPanel, contribLevel, settings, DARKER_LEFT, cal.date); - } - else if (settings.type === 'rainbow') { - addRainbowColor(leftPanel, contribLevel, settings, DARKER_LEFT, week); - } - else if (settings.type === 'bitmap') { - addBitmapPattern(leftPanel, contribLevel, 'left'); - } - if (isAnimate && contribLevel !== 0) { - leftPanel - .append('animate') - .attr('attributeName', 'height') - .attr('values', `${util.toFixed(3 / scaleLeft)};${util.toFixed(heightLeft)}`) - .attr('dur', '3s') - .attr('repeatCount', '1'); - } - const widthRight = settings.type === 'bitmap' - ? Math.max(1, settings.contribPatterns[contribLevel].right.width) - : dxx; - const scaleRight = Math.sqrt(dxx ** 2 + dyy ** 2) / widthRight; - const heightRight = calHeight / scaleRight; - const rightPanel = bar - .append('rect') - .attr('stroke', 'none') - .attr('x', 0) - .attr('y', 0) - .attr('width', util.toFixed(widthRight)) - .attr('height', util.toFixed(heightRight)) - .attr('transform', `translate(${util.toFixed(dxx)} ${util.toFixed(dyy)}) skewY(${-ANGLE}) scale(${util.toFixed(dxx / widthRight)} ${util.toFixed(scaleRight)})`); - if (settings.type === 'normal') { - addNormalColor(rightPanel, contribLevel, settings, DARKER_RIGHT); - } - else if (settings.type === 'season') { - addSeasonColor(rightPanel, contribLevel, settings, DARKER_RIGHT, cal.date); - } - else if (settings.type === 'rainbow') { - addRainbowColor(rightPanel, contribLevel, settings, DARKER_RIGHT, week); - } - else if (settings.type === 'bitmap') { - addBitmapPattern(rightPanel, contribLevel, 'right'); - } - if (isAnimate && contribLevel !== 0) { - rightPanel - .append('animate') - .attr('attributeName', 'height') - .attr('values', `${util.toFixed(3 / scaleRight)};${util.toFixed(heightRight)}`) - .attr('dur', '3s') - .attr('repeatCount', '1'); - } - }); -}; -exports.create3DContrib = create3DContrib; -//# sourceMappingURL=create-3d-contrib.js.map + // "Advance position by 1." + } + // "If buffer is not empty, it contains either 12 or 18 bits. If it contains + // 12 bits, then discard the last four and interpret the remaining eight as + // an 8-bit big-endian number. If it contains 18 bits, then discard the last + // two and interpret the remaining 16 as two 8-bit big-endian numbers. Append + // the one or two bytes with values equal to those one or two numbers to + // output, in the same order." + if (accumulatedBits === 12) { + buffer >>= 4; + output += String.fromCharCode(buffer); + } else if (accumulatedBits === 18) { + buffer >>= 2; + output += String.fromCharCode((buffer & 0xff00) >> 8); + output += String.fromCharCode(buffer & 0xff); + } + // "Return output." + return output; +} +/** + * A lookup table for atob(), which converts an ASCII character to the + * corresponding six-bit number. + */ -/***/ }), +const keystr = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -/***/ 76599: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +function atobLookup(chr) { + const index = keystr.indexOf(chr); + // Throw exception if character is not in the lookup string; should not be hit in tests + return index < 0 ? undefined : index; +} -"use strict"; +module.exports = atob; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createPieLanguage = void 0; -const d3 = __importStar(__nccwpck_require__(45203)); -const OTHER_NAME = 'other'; -const OTHER_COLOR = '#444444'; -const createPieLanguage = (svg, userInfo, x, y, width, height, settings, isForcedAnimation) => { - if (userInfo.totalContributions === 0) { - return; - } - const languages = userInfo.contributesLanguage.slice(0, 5); - const sumContrib = languages - .map((lang) => lang.contributions) - .reduce((a, b) => a + b, 0); - const otherContributions = userInfo.totalCommitContributions - sumContrib; - if (0 < otherContributions) { - languages.push({ - language: OTHER_NAME, - color: OTHER_COLOR, - contributions: otherContributions, - }); - } - const isAnimate = settings.growingAnimation || isForcedAnimation; - const animeSteps = 5; - const animateOpacity = (num) => Array(languages.length + animeSteps) - .fill('') - .map((d, i) => (i < num ? 0 : Math.min((i - num) / animeSteps, 1))) - .join(';'); - const radius = height / 2; - const margin = radius / 10; - const row = 8; - const offset = (row - languages.length) / 2 + 0.5; - const fontSize = height / row / 1.5; - const pie = d3 - .pie() - .value((d) => d.contributions) - .sortValues(null); - const pieData = pie(languages); - const group = svg.append('g').attr('transform', `translate(${x}, ${y})`); - const groupLabel = group - .append('g') - .attr('transform', `translate(${radius * 2.1}, ${0})`); - // markers for label - const markers = groupLabel - .selectAll(null) - .data(pieData) - .enter() - .append('rect') - .attr('x', 0) - .attr('y', (d) => (d.index + offset) * (height / row) - fontSize / 2) - .attr('width', fontSize) - .attr('height', fontSize) - .attr('fill', (d) => d.data.color) - .attr('stroke', settings.backgroundColor) - .attr('stroke-width', '1px'); - if (isAnimate) { - markers - .append('animate') - .attr('attributeName', 'fill-opacity') - .attr('values', (d, i) => animateOpacity(i)) - .attr('dur', '3s') - .attr('repeatCount', '1'); - } - // labels - const labels = groupLabel - .selectAll(null) - .data(pieData) - .enter() - .append('text') - .attr('dominant-baseline', 'middle') - .text((d) => d.data.language) - .attr('x', fontSize * 1.2) - .attr('y', (d) => (d.index + offset) * (height / row)) - .attr('fill', settings.foregroundColor) - .attr('font-size', `${fontSize}px`); - if (isAnimate) { - labels - .append('animate') - .attr('attributeName', 'fill-opacity') - .attr('values', (d, i) => animateOpacity(i)) - .attr('dur', '3s') - .attr('repeatCount', '1'); - } - const arc = d3 - .arc() - .outerRadius(radius - margin) - .innerRadius(radius / 2); - // pie chart - const paths = group - .append('g') - .attr('transform', `translate(${radius}, ${radius})`) - .selectAll(null) - .data(pieData) - .enter() - .append('path') - .attr('d', arc) - .style('fill', (d) => d.data.color) - .attr('stroke', settings.backgroundColor) - .attr('stroke-width', '2px'); - paths - .append('title') - .text((d) => `${d.data.language} ${d.data.contributions}`); - if (isAnimate) { - paths - .append('animate') - .attr('attributeName', 'fill-opacity') - .attr('values', (d, i) => animateOpacity(i)) - .attr('dur', '3s') - .attr('repeatCount', '1'); - } -}; -exports.createPieLanguage = createPieLanguage; -//# sourceMappingURL=create-pie-language.js.map /***/ }), -/***/ 76592: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 50012: +/***/ ((module) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createRadarContrib = void 0; -const util = __importStar(__nccwpck_require__(21458)); -const rangeLabels = ['1', '10', '100', '1K', '10K']; -const levels = rangeLabels.length; -const radians = 2 * Math.PI; -const toLevel = (value) => { - if (value < 1) { - return 0.8; + +/** + * btoa() as defined by the HTML and Infra specs, which mostly just references + * RFC 4648. + */ +function btoa(s) { + let i; + // String conversion as required by Web IDL. + s = `${s}`; + // "The btoa() method must throw an "InvalidCharacterError" DOMException if + // data contains any character whose code point is greater than U+00FF." + for (i = 0; i < s.length; i++) { + if (s.charCodeAt(i) > 255) { + return null; } - const result = Math.log10(value); - return Math.min(result, 5) + 1; -}; -const createRadarContrib = (svg, userInfo, x, y, width, height, settings, isForcedAnimation) => { - const radius = (height / 2) * 0.8; - const cx = width / 2; - const cy = (height / 2) * 1.1; - const isAnimate = settings.growingAnimation || isForcedAnimation; - const commitLabel = settings.l10n ? settings.l10n.commit : 'Commit'; - const issueLabel = settings.l10n ? settings.l10n.issue : 'Issue'; - const pullReqLabel = settings.l10n ? settings.l10n.pullreq : 'PullReq'; - const reviewLabel = settings.l10n ? settings.l10n.review : 'Review'; - const RepoLabel = settings.l10n ? settings.l10n.repo : 'Repo'; - const data = [ - { - name: commitLabel, - value: userInfo.totalCommitContributions, - }, - { - name: issueLabel, - value: userInfo.totalIssueContributions, - }, - { - name: pullReqLabel, - value: userInfo.totalPullRequestContributions, - }, - { - name: reviewLabel, - value: userInfo.totalPullRequestReviewContributions, - }, - { - name: RepoLabel, - value: userInfo.totalRepositoryContributions, - }, - ]; - const total = data.length; - const posX = (level, num) => util.toFixed(radius * (level / levels) * Math.sin((num / total) * radians)); - const posY = (level, num) => util.toFixed(radius * (level / levels) * -Math.cos((num / total) * radians)); - const group = svg - .append('g') - .attr('transform', `translate(${util.toFixed(x + cx)}, ${util.toFixed(y + cy)})`); - for (let j = 0; j < levels; j++) { - group - .selectAll(null) - .data(data) - .enter() - .append('line') - .attr('x1', (d, i) => posX(j + 1, i)) - .attr('y1', (d, i) => posY(j + 1, i)) - .attr('x2', (d, i) => posX(j + 1, i + 1)) - .attr('y2', (d, i) => posY(j + 1, i + 1)) - .style('stroke', settings.weakColor) - .style('stroke-dasharray', '4 4') - .style('stroke-width', '1px'); + } + let out = ""; + for (i = 0; i < s.length; i += 3) { + const groupsOfSix = [undefined, undefined, undefined, undefined]; + groupsOfSix[0] = s.charCodeAt(i) >> 2; + groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4; + if (s.length > i + 1) { + groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4; + groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2; } - group - .selectAll(null) - .data(rangeLabels) - .enter() - .append('text') - .text((d) => d) - .style('font-size', `${util.toFixed(radius / 12)}px`) - .attr('text-anchor', 'start') - .attr('dominant-baseline', 'auto') - .attr('x', util.toFixed(radius / 50)) - .attr('y', (d, i) => util.toFixed(-radius * ((i + 1) / levels))) - .attr('fill', settings.weakColor); - const axis = group - .selectAll(null) - .data(data) - .enter() - .append('g') - .attr('class', 'axis'); - axis.append('line') - .attr('x1', (d, i) => posX(1, i)) - .attr('y1', (d, i) => posY(1, i)) - .attr('x2', (d, i) => posX(levels, i)) - .attr('y2', (d, i) => posY(levels, i)) - .style('stroke', settings.weakColor) - .style('stroke-dasharray', '4 4') - .style('stroke-width', '1px'); - axis.append('text') - .text((d) => d.name) - .style('font-size', `${util.toFixed(radius / 7.5)}px`) - .attr('text-anchor', 'middle') - .attr('dominant-baseline', 'middle') - .attr('x', (d, i) => posX(1.25 * levels, i)) - .attr('y', (d, i) => posY(1.17 * levels, i)) - .attr('fill', settings.foregroundColor) - .append('title') - .text((d) => d.value); - const points = data - .map((d) => toLevel(d.value)) - .map((level, i) => `${posX(level, i)},${posY(level, i)}`) - .join(' '); - const radar = group - .append('polygon') - .style('stroke-width', '4px') - .style('stroke', settings.radarColor) - .attr('points', points) - .style('fill', settings.radarColor) - .style('fill-opacity', 0.5); - if (isAnimate) { - const level0 = toLevel(0); - const points0 = data - .map((d, i) => `${posX(level0, i)},${posY(level0, i)}`) - .join(' '); - radar - .append('animate') - .attr('attributeName', 'points') - .attr('values', `${points0};${points}`) - .attr('dur', '3s') - .attr('repeatCount', '1'); + if (s.length > i + 2) { + groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6; + groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f; } -}; -exports.createRadarContrib = createRadarContrib; -//# sourceMappingURL=create-radar-contrib.js.map + for (let j = 0; j < groupsOfSix.length; j++) { + if (typeof groupsOfSix[j] === "undefined") { + out += "="; + } else { + out += btoaLookup(groupsOfSix[j]); + } + } + } + return out; +} -/***/ }), +/** + * Lookup table for btoa(), which converts a six-bit number into the + * corresponding ASCII character. + */ +const keystr = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -/***/ 50951: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +function btoaLookup(index) { + if (index >= 0 && index < 64) { + return keystr[index]; + } -"use strict"; + // Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests. + return undefined; +} + +module.exports = btoa; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createSvg = void 0; -const d3 = __importStar(__nccwpck_require__(45203)); -const jsdom_1 = __nccwpck_require__(46123); -const contrib = __importStar(__nccwpck_require__(78739)); -const pie = __importStar(__nccwpck_require__(76599)); -const radar = __importStar(__nccwpck_require__(76592)); -const util = __importStar(__nccwpck_require__(21458)); -const width = 1280; -const height = 850; -const pieHeight = 200 * 1.3; -const pieWidth = pieHeight * 2; -const radarWidth = 400 * 1.3; -const radarHeight = (radarWidth * 3) / 4; -const radarX = width - radarWidth - 40; -const createSvg = (userInfo, settings, isForcedAnimation) => { - let svgWidth = width; - let svgHeight = height; - if (settings.type === 'pie_lang_only') { - svgWidth = pieWidth; - svgHeight = pieHeight; - } - else if (settings.type === 'radar_contrib_only') { - svgWidth = radarWidth; - svgHeight = radarHeight; - } - const fakeDom = new jsdom_1.JSDOM('
'); - const container = d3.select(fakeDom.window.document).select('.container'); - const svg = container - .append('svg') - .attr('xmlns', 'http://www.w3.org/2000/svg') - .attr('width', svgWidth) - .attr('height', svgHeight) - .attr('viewBox', `0 0 ${svgWidth} ${svgHeight}`); - svg.append('style').html('* { font-family: "Ubuntu", "Helvetica", "Arial", sans-serif; }'); - contrib.addDefines(svg, settings); - // background - svg.append('rect') - .attr('x', 0) - .attr('y', 0) - .attr('width', svgWidth) - .attr('height', svgHeight) - .attr('fill', settings.backgroundColor); - if (settings.type === 'pie_lang_only') { - // pie chart only - pie.createPieLanguage(svg, userInfo, 0, 0, pieWidth, pieHeight, settings, isForcedAnimation); - } - else if (settings.type === 'radar_contrib_only') { - // radar chart only - radar.createRadarContrib(svg, userInfo, 0, 0, radarWidth, radarHeight, settings, isForcedAnimation); - } - else { - // 3D-Contrib Calendar - contrib.create3DContrib(svg, userInfo, 0, 0, width, height, settings, isForcedAnimation); - // radar chart - radar.createRadarContrib(svg, userInfo, radarX, 70, radarWidth, radarHeight, settings, isForcedAnimation); - // pie chart - pie.createPieLanguage(svg, userInfo, 40, height - pieHeight - 70, pieWidth, pieHeight, settings, isForcedAnimation); - const group = svg.append('g'); - const positionXContrib = (width * 3) / 10; - const positionYContrib = height - 20; - group - .append('text') - .style('font-size', '32px') - .style('font-weight', 'bold') - .attr('x', positionXContrib) - .attr('y', positionYContrib) - .attr('text-anchor', 'end') - .text(util.inertThousandSeparator(userInfo.totalContributions)) - .attr('fill', settings.strongColor); - const contribLabel = settings.l10n - ? settings.l10n.contrib - : 'contributions'; - group - .append('text') - .style('font-size', '24px') - .attr('x', positionXContrib + 10) - .attr('y', positionYContrib) - .attr('text-anchor', 'start') - .attr('text-anchor', 'start') - .text(contribLabel) - .attr('fill', settings.foregroundColor); - const positionXStar = (width * 5) / 10; - const positionYStar = positionYContrib; - // icon of star - group - .append('g') - .attr('transform', `translate(${positionXStar - 32}, ${positionYStar - 28}), scale(2)`) - .append('path') - .attr('fill-rule', 'evenodd') - .attr('d', 'M8 .25a.75.75 0 01.673.418l1.882 3.815 4.21.612a.75.75 0 01.416 1.279l-3.046 2.97.719 4.192a.75.75 0 01-1.088.791L8 12.347l-3.766 1.98a.75.75 0 01-1.088-.79l.72-4.194L.818 6.374a.75.75 0 01.416-1.28l4.21-.611L7.327.668A.75.75 0 018 .25zm0 2.445L6.615 5.5a.75.75 0 01-.564.41l-3.097.45 2.24 2.184a.75.75 0 01.216.664l-.528 3.084 2.769-1.456a.75.75 0 01.698 0l2.77 1.456-.53-3.084a.75.75 0 01.216-.664l2.24-2.183-3.096-.45a.75.75 0 01-.564-.41L8 2.694v.001z') - .attr('fill', settings.foregroundColor); - group - .append('text') - .style('font-size', '32px') - .style('font-weight', 'bold') - .attr('x', positionXStar + 10) - .attr('y', positionYStar) - .attr('text-anchor', 'start') - .text(util.toScale(userInfo.totalStargazerCount)) - .attr('fill', settings.foregroundColor) - .append('title') - .text(userInfo.totalStargazerCount); - const positionXFork = (width * 6) / 10; - const positionYFork = positionYContrib; - // icon of fork - group - .append('g') - .attr('transform', `translate(${positionXFork - 32}, ${positionYFork - 28}), scale(2)`) - .append('path') - .attr('fill-rule', 'evenodd') - .attr('d', 'M5 3.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm0 2.122a2.25 2.25 0 10-1.5 0v.878A2.25 2.25 0 005.75 8.5h1.5v2.128a2.251 2.251 0 101.5 0V8.5h1.5a2.25 2.25 0 002.25-2.25v-.878a2.25 2.25 0 10-1.5 0v.878a.75.75 0 01-.75.75h-4.5A.75.75 0 015 6.25v-.878zm3.75 7.378a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm3-8.75a.75.75 0 100-1.5.75.75 0 000 1.5z') - .attr('fill', settings.foregroundColor); - group - .append('text') - .style('font-size', '32px') - .style('font-weight', 'bold') - .attr('x', positionXFork + 4) - .attr('y', positionYFork) - .attr('text-anchor', 'start') - .text(util.toScale(userInfo.totalForkCount)) - .attr('fill', settings.foregroundColor) - .append('title') - .text(userInfo.totalForkCount); - // ISO 8601 format - const startDate = userInfo.contributionCalendar[0].date; - const endDate = userInfo.contributionCalendar[userInfo.contributionCalendar.length - 1].date; - const period = `${util.toIsoDate(startDate)} / ${util.toIsoDate(endDate)}`; - group - .append('text') - .style('font-size', '16px') - .attr('x', width - 20) - .attr('y', 20) - .attr('dominant-baseline', 'hanging') - .attr('text-anchor', 'end') - .text(period) - .attr('fill', settings.weakColor); - } - return container.html(); -}; -exports.createSvg = createSvg; -//# sourceMappingURL=create-svg.js.map /***/ }), -/***/ 10302: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 64941: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.writeFile = exports.OUTPUT_FOLDER = void 0; -const fs_1 = __nccwpck_require__(35747); -exports.OUTPUT_FOLDER = './profile-3d-contrib'; -const writeFile = (fileName, content) => { - fs_1.mkdirSync(exports.OUTPUT_FOLDER, { recursive: true }); - fs_1.writeFileSync(`${exports.OUTPUT_FOLDER}/${fileName}`, content); -}; -exports.writeFile = writeFile; -//# sourceMappingURL=file-writer.js.map -/***/ }), +var compileSchema = __nccwpck_require__(875) + , resolve = __nccwpck_require__(63896) + , Cache = __nccwpck_require__(93679) + , SchemaObject = __nccwpck_require__(37605) + , stableStringify = __nccwpck_require__(30969) + , formats = __nccwpck_require__(66627) + , rules = __nccwpck_require__(68561) + , $dataMetaSchema = __nccwpck_require__(21412) + , util = __nccwpck_require__(76578); -/***/ 44981: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +module.exports = Ajv; -"use strict"; +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fetchData = exports.fetchNext = exports.fetchFirst = exports.URL = void 0; -const axios_1 = __importDefault(__nccwpck_require__(96545)); -exports.URL = 'https://api.github.com/graphql'; -const maxReposOneQuery = 100; -const fetchFirst = async (token, userName) => { - const headers = { - Authorization: `bearer ${token}`, - }; - const request = { - query: ` - query($login: String!) { - user(login: $login) { - contributionsCollection { - contributionCalendar { - isHalloween - totalContributions - weeks { - contributionDays { - contributionCount - contributionLevel - date - } - } - } - commitContributionsByRepository(maxRepositories: ${maxReposOneQuery}) { - repository { - primaryLanguage { - name - color - } - } - contributions { - totalCount - } - } - totalCommitContributions - totalIssueContributions - totalPullRequestContributions - totalPullRequestReviewContributions - totalRepositoryContributions - } - repositories(first: ${maxReposOneQuery}, ownerAffiliations: OWNER) { - edges { - cursor - } - nodes { - forkCount - stargazerCount - } - } - } - } - `.replace(/\s+/g, ' '), - variables: { login: userName }, - }; - const response = await axios_1.default.post(exports.URL, request, { - headers: headers, - }); - return response.data; -}; -exports.fetchFirst = fetchFirst; -const fetchNext = async (token, userName, cursor) => { - const headers = { - Authorization: `bearer ${token}`, - }; - const request = { - query: ` - query($login: String!, $cursor: String!) { - user(login: $login) { - repositories(after: $cursor, first: ${maxReposOneQuery}, ownerAffiliations: OWNER) { - edges { - cursor - } - nodes { - forkCount - stargazerCount - } - } - } - } - `.replace(/\s+/g, ' '), - variables: { - login: userName, - cursor: cursor, - }, - }; - const response = await axios_1.default.post(exports.URL, request, { - headers: headers, - }); - return response.data; -}; -exports.fetchNext = fetchNext; -/** Fetch data from GitHub GraphQL */ -const fetchData = async (token, userName, maxRepos) => { - const res1 = await exports.fetchFirst(token, userName); - const result = res1.data; - if (result && result.user.repositories.nodes.length === maxReposOneQuery) { - const repos1 = result.user.repositories; - let cursor = repos1.edges[repos1.edges.length - 1].cursor; - while (repos1.nodes.length < maxRepos) { - const res2 = await exports.fetchNext(token, userName, cursor); - if (res2.data) { - const repos2 = res2.data.user.repositories; - repos1.nodes.push(...repos2.nodes); - if (repos2.nodes.length !== maxReposOneQuery) { - break; - } - cursor = repos2.edges[repos2.edges.length - 1].cursor; - } - else { - break; - } - } - } - return res1; -}; -exports.fetchData = fetchData; -//# sourceMappingURL=github-graphql.js.map +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; -/***/ }), +Ajv.prototype.compileAsync = __nccwpck_require__(80890); +var customKeyword = __nccwpck_require__(53297); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.prototype.validateKeyword = customKeyword.validate; -/***/ 98401: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +var errorClasses = __nccwpck_require__(25726); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; -"use strict"; +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.main = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const aggregate = __importStar(__nccwpck_require__(34734)); -const template = __importStar(__nccwpck_require__(67007)); -const create = __importStar(__nccwpck_require__(50951)); -const f = __importStar(__nccwpck_require__(10302)); -const r = __importStar(__nccwpck_require__(30062)); -const client = __importStar(__nccwpck_require__(44981)); -const main = async () => { - try { - const token = process.env.GITHUB_TOKEN; - if (!token) { - core.setFailed('GITHUB_TOKEN is empty'); - return; - } - const userName = 3 <= process.argv.length ? process.argv[2] : process.env.USERNAME; - if (!userName) { - core.setFailed('USERNAME is empty'); - return; - } - const maxRepos = process.env.MAX_REPOS - ? Number(process.env.MAX_REPOS) - : 100; - if (Number.isNaN(maxRepos)) { - core.setFailed('MAX_REPOS is NaN'); - return; - } - const response = await client.fetchData(token, userName, maxRepos); - const userInfo = aggregate.aggregateUserInfo(response); - if (process.env.SETTING_JSON) { - const settingFile = r.readSettingJson(process.env.SETTING_JSON); - const settingInfos = 'length' in settingFile ? settingFile : [settingFile]; - for (const settingInfo of settingInfos) { - const fileName = settingInfo.fileName || 'profile-customize.svg'; - f.writeFile(fileName, create.createSvg(userInfo, settingInfo, false)); - } - } - else { - const settings = userInfo.isHalloween - ? template.HalloweenSettings - : template.NormalSettings; - f.writeFile('profile-green-animate.svg', create.createSvg(userInfo, settings, true)); - f.writeFile('profile-green.svg', create.createSvg(userInfo, settings, false)); - // Northern hemisphere - f.writeFile('profile-season-animate.svg', create.createSvg(userInfo, template.NorthSeasonSettings, true)); - f.writeFile('profile-season.svg', create.createSvg(userInfo, template.NorthSeasonSettings, false)); - // Southern hemisphere - f.writeFile('profile-south-season-animate.svg', create.createSvg(userInfo, template.SouthSeasonSettings, true)); - f.writeFile('profile-south-season.svg', create.createSvg(userInfo, template.SouthSeasonSettings, false)); - f.writeFile('profile-night-view.svg', create.createSvg(userInfo, template.NightViewSettings, true)); - f.writeFile('profile-night-green.svg', create.createSvg(userInfo, template.NightGreenSettings, true)); - f.writeFile('profile-night-rainbow.svg', create.createSvg(userInfo, template.NightRainbowSettings, true)); - f.writeFile('profile-gitblock.svg', create.createSvg(userInfo, template.GitBlockSettings, true)); - } - } - catch (error) { - console.error(error); - core.setFailed('error'); - } -}; -exports.main = main; -void exports.main(); -//# sourceMappingURL=index.js.map +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; +var META_SUPPORT_DATA = ['/properties']; -/***/ }), +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + setLogger(this); + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); -/***/ 30062: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); -"use strict"; + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.readSettingJson = void 0; -const fs_1 = __nccwpck_require__(35747); -const readSettingJson = (filePath) => { - const content = fs_1.readFileSync(filePath, { - encoding: 'utf8', - flag: 'r', - }); - return JSON.parse(content); -}; -exports.readSettingJson = readSettingJson; -//# sourceMappingURL=settings-reader.js.map + if (opts.formats) addInitialFormats(this); + if (opts.keywords) addInitialKeywords(this); + addDefaultMetaSchema(this); + if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); + if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); + addInitialSchemas(this); +} -/***/ }), -/***/ 21458: -/***/ ((__unused_webpack_module, exports) => { -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toFixed = exports.toScale = exports.inertThousandSeparator = exports.toIsoDate = void 0; -const toIsoDate = (date) => date.toISOString().substring(0, 10); -exports.toIsoDate = toIsoDate; -const inertThousandSeparator = (value) => { - if (value <= 9999) { - // 4 digits or less, do not need to be separated. - // e.g. "1234" - return value.toFixed(0); - } - // 5 digits or more, separate each 3 digits with a space(SI format). - // e.g. "12 345" - return value.toFixed(0).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1 '); -}; -exports.inertThousandSeparator = inertThousandSeparator; -/** Round large numbers */ -const toScale = (value) => { - if (value <= 9999) { - // 0 - 9999 - return value.toFixed(0); - } - else if (value <= 999999) { - // 10K - 999K - return Math.floor(value / 1000).toFixed(0) + 'K'; - } - else { - return '1M+'; - } -}; -exports.toScale = toScale; -/** Round to two decimal places. */ -const toFixed = (value) => +value.toFixed(2); -exports.toFixed = toFixed; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 87351: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const os = __importStar(__nccwpck_require__(12087)); -const utils_1 = __nccwpck_require__(5278); -/** - * Commands - * - * Command Format: - * ::name key=value,key=value::message - * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value - */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); -} -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; - } - this.command = command; - this.properties = properties; - this.message = message; - } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; - } -} -function escapeData(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); -} -function escapeProperty(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); -} -//# sourceMappingURL=command.js.map - -/***/ }), - -/***/ 42186: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const command_1 = __nccwpck_require__(87351); -const file_command_1 = __nccwpck_require__(717); -const utils_1 = __nccwpck_require__(5278); -const os = __importStar(__nccwpck_require__(12087)); -const path = __importStar(__nccwpck_require__(85622)); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - const delimiter = '_GitHubActionsFileCommandDelimeter_'; - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); - } - else { - command_1.issueCommand('set-env', { name }, convertedVal); - } -} -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); -} -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - file_command_1.issueCommand('PATH', inputPath); - } - else { - command_1.issueCommand('add-path', {}, inputPath); - } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; -} -exports.addPath = addPath; -/** - * Gets the value of an input. The value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - return val.trim(); -} -exports.getInput = getInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, value); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - command_1.issueCommand('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - */ -function error(message) { - command_1.issue('error', message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds an warning issue - * @param message warning issue message. Errors will be converted to string via toString() - */ -function warning(message) { - command_1.issue('warning', message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - command_1.issue('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - command_1.issue('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group - */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); - } - return result; - }); -} -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); -} -exports.saveState = saveState; -/** - * Gets the value of an state set by this action's main execution. - * - * @param name name of the state to get - * @returns string - */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -//# sourceMappingURL=core.js.map - -/***/ }), - -/***/ 717: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// For internal use, subject to change. -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(35747)); -const os = __importStar(__nccwpck_require__(12087)); -const utils_1 = __nccwpck_require__(5278); -function issueCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); - } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); - } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { - encoding: 'utf8' - }); -} -exports.issueCommand = issueCommand; -//# sourceMappingURL=file-command.js.map - -/***/ }), - -/***/ 5278: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; - } - return JSON.stringify(input); -} -exports.toCommandValue = toCommandValue; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 75696: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const atob = __nccwpck_require__(84732); -const btoa = __nccwpck_require__(50012); - -module.exports = { - atob, - btoa -}; - - -/***/ }), - -/***/ 84732: -/***/ ((module) => { - -"use strict"; - - -/** - * Implementation of atob() according to the HTML and Infra specs, except that - * instead of throwing INVALID_CHARACTER_ERR we return null. - */ -function atob(data) { - // Web IDL requires DOMStrings to just be converted using ECMAScript - // ToString, which in our case amounts to using a template literal. - data = `${data}`; - // "Remove all ASCII whitespace from data." - data = data.replace(/[ \t\n\f\r]/g, ""); - // "If data's length divides by 4 leaving no remainder, then: if data ends - // with one or two U+003D (=) code points, then remove them from data." - if (data.length % 4 === 0) { - data = data.replace(/==?$/, ""); - } - // "If data's length divides by 4 leaving a remainder of 1, then return - // failure." - // - // "If data contains a code point that is not one of - // - // U+002B (+) - // U+002F (/) - // ASCII alphanumeric - // - // then return failure." - if (data.length % 4 === 1 || /[^+/0-9A-Za-z]/.test(data)) { - return null; - } - // "Let output be an empty byte sequence." - let output = ""; - // "Let buffer be an empty buffer that can have bits appended to it." - // - // We append bits via left-shift and or. accumulatedBits is used to track - // when we've gotten to 24 bits. - let buffer = 0; - let accumulatedBits = 0; - // "Let position be a position variable for data, initially pointing at the - // start of data." - // - // "While position does not point past the end of data:" - for (let i = 0; i < data.length; i++) { - // "Find the code point pointed to by position in the second column of - // Table 1: The Base 64 Alphabet of RFC 4648. Let n be the number given in - // the first cell of the same row. - // - // "Append to buffer the six bits corresponding to n, most significant bit - // first." - // - // atobLookup() implements the table from RFC 4648. - buffer <<= 6; - buffer |= atobLookup(data[i]); - accumulatedBits += 6; - // "If buffer has accumulated 24 bits, interpret them as three 8-bit - // big-endian numbers. Append three bytes with values equal to those - // numbers to output, in the same order, and then empty buffer." - if (accumulatedBits === 24) { - output += String.fromCharCode((buffer & 0xff0000) >> 16); - output += String.fromCharCode((buffer & 0xff00) >> 8); - output += String.fromCharCode(buffer & 0xff); - buffer = accumulatedBits = 0; - } - // "Advance position by 1." - } - // "If buffer is not empty, it contains either 12 or 18 bits. If it contains - // 12 bits, then discard the last four and interpret the remaining eight as - // an 8-bit big-endian number. If it contains 18 bits, then discard the last - // two and interpret the remaining 16 as two 8-bit big-endian numbers. Append - // the one or two bytes with values equal to those one or two numbers to - // output, in the same order." - if (accumulatedBits === 12) { - buffer >>= 4; - output += String.fromCharCode(buffer); - } else if (accumulatedBits === 18) { - buffer >>= 2; - output += String.fromCharCode((buffer & 0xff00) >> 8); - output += String.fromCharCode(buffer & 0xff); - } - // "Return output." - return output; -} -/** - * A lookup table for atob(), which converts an ASCII character to the - * corresponding six-bit number. - */ - -const keystr = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -function atobLookup(chr) { - const index = keystr.indexOf(chr); - // Throw exception if character is not in the lookup string; should not be hit in tests - return index < 0 ? undefined : index; -} - -module.exports = atob; - - -/***/ }), - -/***/ 50012: -/***/ ((module) => { - -"use strict"; - - -/** - * btoa() as defined by the HTML and Infra specs, which mostly just references - * RFC 4648. - */ -function btoa(s) { - let i; - // String conversion as required by Web IDL. - s = `${s}`; - // "The btoa() method must throw an "InvalidCharacterError" DOMException if - // data contains any character whose code point is greater than U+00FF." - for (i = 0; i < s.length; i++) { - if (s.charCodeAt(i) > 255) { - return null; - } - } - let out = ""; - for (i = 0; i < s.length; i += 3) { - const groupsOfSix = [undefined, undefined, undefined, undefined]; - groupsOfSix[0] = s.charCodeAt(i) >> 2; - groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4; - if (s.length > i + 1) { - groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4; - groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2; - } - if (s.length > i + 2) { - groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6; - groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f; - } - for (let j = 0; j < groupsOfSix.length; j++) { - if (typeof groupsOfSix[j] === "undefined") { - out += "="; - } else { - out += btoaLookup(groupsOfSix[j]); - } - } - } - return out; -} - -/** - * Lookup table for btoa(), which converts a six-bit number into the - * corresponding ASCII character. - */ -const keystr = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -function btoaLookup(index) { - if (index >= 0 && index < 64) { - return keystr[index]; - } - - // Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests. - return undefined; -} - -module.exports = btoa; - - -/***/ }), - -/***/ 64941: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var compileSchema = __nccwpck_require__(875) - , resolve = __nccwpck_require__(63896) - , Cache = __nccwpck_require__(93679) - , SchemaObject = __nccwpck_require__(37605) - , stableStringify = __nccwpck_require__(30969) - , formats = __nccwpck_require__(66627) - , rules = __nccwpck_require__(68561) - , $dataMetaSchema = __nccwpck_require__(21412) - , util = __nccwpck_require__(76578); - -module.exports = Ajv; - -Ajv.prototype.validate = validate; -Ajv.prototype.compile = compile; -Ajv.prototype.addSchema = addSchema; -Ajv.prototype.addMetaSchema = addMetaSchema; -Ajv.prototype.validateSchema = validateSchema; -Ajv.prototype.getSchema = getSchema; -Ajv.prototype.removeSchema = removeSchema; -Ajv.prototype.addFormat = addFormat; -Ajv.prototype.errorsText = errorsText; - -Ajv.prototype._addSchema = _addSchema; -Ajv.prototype._compile = _compile; - -Ajv.prototype.compileAsync = __nccwpck_require__(80890); -var customKeyword = __nccwpck_require__(53297); -Ajv.prototype.addKeyword = customKeyword.add; -Ajv.prototype.getKeyword = customKeyword.get; -Ajv.prototype.removeKeyword = customKeyword.remove; -Ajv.prototype.validateKeyword = customKeyword.validate; - -var errorClasses = __nccwpck_require__(25726); -Ajv.ValidationError = errorClasses.Validation; -Ajv.MissingRefError = errorClasses.MissingRef; -Ajv.$dataMetaSchema = $dataMetaSchema; - -var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; - -var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; -var META_SUPPORT_DATA = ['/properties']; - -/** - * Creates validator instance. - * Usage: `Ajv(opts)` - * @param {Object} opts optional options - * @return {Object} ajv instance - */ -function Ajv(opts) { - if (!(this instanceof Ajv)) return new Ajv(opts); - opts = this._opts = util.copy(opts) || {}; - setLogger(this); - this._schemas = {}; - this._refs = {}; - this._fragments = {}; - this._formats = formats(opts.format); - - this._cache = opts.cache || new Cache; - this._loadingSchemas = {}; - this._compilations = []; - this.RULES = rules(); - this._getId = chooseGetId(opts); - - opts.loopRequired = opts.loopRequired || Infinity; - if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; - if (opts.serialize === undefined) opts.serialize = stableStringify; - this._metaOpts = getMetaSchemaOptions(this); - - if (opts.formats) addInitialFormats(this); - if (opts.keywords) addInitialKeywords(this); - addDefaultMetaSchema(this); - if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); - if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); - addInitialSchemas(this); -} - - - -/** - * Validate data using schema - * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. - * @this Ajv - * @param {String|Object} schemaKeyRef key, ref or schema object - * @param {Any} data to be validated - * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). - */ -function validate(schemaKeyRef, data) { - var v; - if (typeof schemaKeyRef == 'string') { - v = this.getSchema(schemaKeyRef); - if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); - } else { - var schemaObj = this._addSchema(schemaKeyRef); - v = schemaObj.validate || this._compile(schemaObj); - } +/** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ +function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + v = schemaObj.validate || this._compile(schemaObj); + } var valid = v(data); if (v.$async !== true) this.errors = v.errors; @@ -2634,11 +1030,11 @@ function addFormat(name, format) { function addDefaultMetaSchema(self) { var $dataSchema; if (self._opts.$data) { - $dataSchema = __nccwpck_require__(66835); + $dataSchema = __nccwpck_require__(894); self.addMetaSchema($dataSchema, $dataSchema.$id, true); } if (self._opts.meta === false) return; - var metaSchema = __nccwpck_require__(40038); + var metaSchema = __nccwpck_require__(6680); if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA); self.addMetaSchema(metaSchema, META_SCHEMA_ID, true); self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; @@ -2741,7 +1137,7 @@ Cache.prototype.clear = function Cache_clear() { "use strict"; -var MissingRefError = __nccwpck_require__(25726).MissingRef; +var MissingRefError = (__nccwpck_require__(25726).MissingRef); module.exports = compileAsync; @@ -3705,7 +2101,7 @@ function resolveIds(schema) { var ruleModules = __nccwpck_require__(85810) - , toHash = __nccwpck_require__(76578).toHash; + , toHash = (__nccwpck_require__(76578).toHash); module.exports = function rules() { var RULES = [ @@ -4127,7 +2523,7 @@ module.exports = function (metaSchema, keywordsJsonPointers) { "use strict"; -var metaSchema = __nccwpck_require__(40038); +var metaSchema = __nccwpck_require__(6680); module.exports = { $id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js', @@ -7839,8 +6235,8 @@ for (var e in errors) { // Copyright 2011 Mark Cavage All rights reserved. -var assert = __nccwpck_require__(42357); -var Buffer = __nccwpck_require__(15118).Buffer; +var assert = __nccwpck_require__(39491); +var Buffer = (__nccwpck_require__(15118).Buffer); var ASN1 = __nccwpck_require__(42473); var errors = __nccwpck_require__(99348); @@ -8151,8 +6547,8 @@ module.exports = { // Copyright 2011 Mark Cavage All rights reserved. -var assert = __nccwpck_require__(42357); -var Buffer = __nccwpck_require__(15118).Buffer; +var assert = __nccwpck_require__(39491); +var Buffer = (__nccwpck_require__(15118).Buffer); var ASN1 = __nccwpck_require__(42473); var errors = __nccwpck_require__(99348); @@ -8503,9 +6899,9 @@ module.exports = { // Copyright (c) 2012, Mark Cavage. All rights reserved. // Copyright 2015 Joyent, Inc. -var assert = __nccwpck_require__(42357); -var Stream = __nccwpck_require__(92413).Stream; -var util = __nccwpck_require__(31669); +var assert = __nccwpck_require__(39491); +var Stream = (__nccwpck_require__(12781).Stream); +var util = __nccwpck_require__(73837); ///--- Globals @@ -9180,8 +7576,8 @@ function descending(a, b) * Module dependencies. */ -var crypto = __nccwpck_require__(76417) - , parse = __nccwpck_require__(78835).parse +var crypto = __nccwpck_require__(6113) + , parse = (__nccwpck_require__(57310).parse) ; /** @@ -9379,9 +7775,9 @@ module.exports.canonicalizeResource = canonicalizeResource /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var aws4 = exports, - url = __nccwpck_require__(78835), - querystring = __nccwpck_require__(71191), - crypto = __nccwpck_require__(76417), + url = __nccwpck_require__(57310), + querystring = __nccwpck_require__(63477), + crypto = __nccwpck_require__(6113), lru = __nccwpck_require__(74225), credentialsCache = lru(1000) @@ -9875,13 +8271,13 @@ var utils = __nccwpck_require__(20328); var settle = __nccwpck_require__(13211); var buildFullPath = __nccwpck_require__(41934); var buildURL = __nccwpck_require__(30646); -var http = __nccwpck_require__(98605); -var https = __nccwpck_require__(57211); -var httpFollow = __nccwpck_require__(67707).http; -var httpsFollow = __nccwpck_require__(67707).https; -var url = __nccwpck_require__(78835); -var zlib = __nccwpck_require__(78761); -var pkg = __nccwpck_require__(20696); +var http = __nccwpck_require__(13685); +var https = __nccwpck_require__(22241); +var httpFollow = (__nccwpck_require__(67707).http); +var httpsFollow = (__nccwpck_require__(67707).https); +var url = __nccwpck_require__(57310); +var zlib = __nccwpck_require__(59796); +var pkg = __nccwpck_require__(88593); var createError = __nccwpck_require__(15226); var enhanceError = __nccwpck_require__(21516); @@ -10422,7 +8818,7 @@ axios.isAxiosError = __nccwpck_require__(60650); module.exports = axios; // Allow use of default import syntax in TypeScript -module.exports.default = axios; +module.exports["default"] = axios; /***/ }), @@ -11926,7 +10322,7 @@ module.exports = { "use strict"; -var crypto_hash_sha512 = __nccwpck_require__(68729).lowlevel.crypto_hash; +var crypto_hash_sha512 = (__nccwpck_require__(68729).lowlevel.crypto_hash); /* * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a @@ -12595,8 +10991,8 @@ module.exports.httpify = function (resp, headers) { /***/ 85443: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var util = __nccwpck_require__(31669); -var Stream = __nccwpck_require__(92413).Stream; +var util = __nccwpck_require__(73837); +var Stream = (__nccwpck_require__(12781).Stream); var DelayedStream = __nccwpck_require__(18611); module.exports = CombinedStream; @@ -12927,8 +11323,8 @@ function objectToString(o) { //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(23364).CSSRule, - MatcherList: __nccwpck_require__(25458).MatcherList + CSSRule: (__nccwpck_require__(23364).CSSRule), + MatcherList: (__nccwpck_require__(25458).MatcherList) }; ///CommonJS @@ -12973,8 +11369,8 @@ exports.CSSDocumentRule = CSSOM.CSSDocumentRule; //.CommonJS var CSSOM = { - CSSStyleDeclaration: __nccwpck_require__(45131).CSSStyleDeclaration, - CSSRule: __nccwpck_require__(23364).CSSRule + CSSStyleDeclaration: (__nccwpck_require__(45131).CSSStyleDeclaration), + CSSRule: (__nccwpck_require__(23364).CSSRule) }; ///CommonJS @@ -13016,7 +11412,7 @@ exports.CSSFontFaceRule = CSSOM.CSSFontFaceRule; //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(23364).CSSRule + CSSRule: (__nccwpck_require__(23364).CSSRule) }; ///CommonJS @@ -13060,9 +11456,9 @@ exports.CSSHostRule = CSSOM.CSSHostRule; //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(23364).CSSRule, - CSSStyleSheet: __nccwpck_require__(62486).CSSStyleSheet, - MediaList: __nccwpck_require__(63849).MediaList + CSSRule: (__nccwpck_require__(23364).CSSRule), + CSSStyleSheet: (__nccwpck_require__(62486).CSSStyleSheet), + MediaList: (__nccwpck_require__(63849).MediaList) }; ///CommonJS @@ -13199,8 +11595,8 @@ exports.CSSImportRule = CSSOM.CSSImportRule; //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(23364).CSSRule, - CSSStyleDeclaration: __nccwpck_require__(45131).CSSStyleDeclaration + CSSRule: (__nccwpck_require__(23364).CSSRule), + CSSStyleDeclaration: (__nccwpck_require__(45131).CSSStyleDeclaration) }; ///CommonJS @@ -13243,7 +11639,7 @@ exports.CSSKeyframeRule = CSSOM.CSSKeyframeRule; //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(23364).CSSRule + CSSRule: (__nccwpck_require__(23364).CSSRule) }; ///CommonJS @@ -13289,8 +11685,8 @@ exports.CSSKeyframesRule = CSSOM.CSSKeyframesRule; //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(23364).CSSRule, - MediaList: __nccwpck_require__(63849).MediaList + CSSRule: (__nccwpck_require__(23364).CSSRule), + MediaList: (__nccwpck_require__(63849).MediaList) }; ///CommonJS @@ -13531,7 +11927,7 @@ CSSOM.CSSStyleDeclaration.prototype = { //.CommonJS exports.CSSStyleDeclaration = CSSOM.CSSStyleDeclaration; -CSSOM.parse = __nccwpck_require__(18025).parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleDeclaration.js +CSSOM.parse = (__nccwpck_require__(18025).parse); // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleDeclaration.js ///CommonJS @@ -13542,8 +11938,8 @@ CSSOM.parse = __nccwpck_require__(18025).parse; // Cannot be included sooner due //.CommonJS var CSSOM = { - CSSStyleDeclaration: __nccwpck_require__(45131).CSSStyleDeclaration, - CSSRule: __nccwpck_require__(23364).CSSRule + CSSStyleDeclaration: (__nccwpck_require__(45131).CSSStyleDeclaration), + CSSRule: (__nccwpck_require__(23364).CSSRule) }; ///CommonJS @@ -13739,8 +12135,8 @@ exports.CSSStyleRule = CSSOM.CSSStyleRule; //.CommonJS var CSSOM = { - StyleSheet: __nccwpck_require__(96785).StyleSheet, - CSSStyleRule: __nccwpck_require__(4608).CSSStyleRule + StyleSheet: (__nccwpck_require__(96785).StyleSheet), + CSSStyleRule: (__nccwpck_require__(4608).CSSStyleRule) }; ///CommonJS @@ -13823,7 +12219,7 @@ CSSOM.CSSStyleSheet.prototype.toString = function() { //.CommonJS exports.CSSStyleSheet = CSSOM.CSSStyleSheet; -CSSOM.parse = __nccwpck_require__(18025).parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleSheet.js +CSSOM.parse = (__nccwpck_require__(18025).parse); // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleSheet.js ///CommonJS @@ -13834,7 +12230,7 @@ CSSOM.parse = __nccwpck_require__(18025).parse; // Cannot be included sooner due //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(23364).CSSRule, + CSSRule: (__nccwpck_require__(23364).CSSRule), }; ///CommonJS @@ -13927,7 +12323,7 @@ exports.CSSValue = CSSOM.CSSValue; //.CommonJS var CSSOM = { - CSSValue: __nccwpck_require__(99957).CSSValue + CSSValue: (__nccwpck_require__(99957).CSSValue) }; ///CommonJS @@ -14439,13 +12835,13 @@ exports.StyleSheet = CSSOM.StyleSheet; //.CommonJS var CSSOM = { - CSSStyleSheet: __nccwpck_require__(62486).CSSStyleSheet, - CSSStyleRule: __nccwpck_require__(4608).CSSStyleRule, - CSSMediaRule: __nccwpck_require__(96791).CSSMediaRule, - CSSSupportsRule: __nccwpck_require__(27967).CSSSupportsRule, - CSSStyleDeclaration: __nccwpck_require__(45131).CSSStyleDeclaration, - CSSKeyframeRule: __nccwpck_require__(97254).CSSKeyframeRule, - CSSKeyframesRule: __nccwpck_require__(16005).CSSKeyframesRule + CSSStyleSheet: (__nccwpck_require__(62486).CSSStyleSheet), + CSSStyleRule: (__nccwpck_require__(4608).CSSStyleRule), + CSSMediaRule: (__nccwpck_require__(96791).CSSMediaRule), + CSSSupportsRule: (__nccwpck_require__(27967).CSSSupportsRule), + CSSStyleDeclaration: (__nccwpck_require__(45131).CSSStyleDeclaration), + CSSKeyframeRule: (__nccwpck_require__(97254).CSSKeyframeRule), + CSSKeyframesRule: (__nccwpck_require__(16005).CSSKeyframesRule) }; ///CommonJS @@ -14994,18 +13390,18 @@ CSSOM.parse = function parse(token) { //.CommonJS exports.parse = CSSOM.parse; // The following modules cannot be included sooner due to the mutual dependency with parse.js -CSSOM.CSSStyleSheet = __nccwpck_require__(62486).CSSStyleSheet; -CSSOM.CSSStyleRule = __nccwpck_require__(4608).CSSStyleRule; -CSSOM.CSSImportRule = __nccwpck_require__(49776).CSSImportRule; -CSSOM.CSSMediaRule = __nccwpck_require__(96791).CSSMediaRule; -CSSOM.CSSSupportsRule = __nccwpck_require__(27967).CSSSupportsRule; -CSSOM.CSSFontFaceRule = __nccwpck_require__(33046).CSSFontFaceRule; -CSSOM.CSSHostRule = __nccwpck_require__(57986).CSSHostRule; -CSSOM.CSSStyleDeclaration = __nccwpck_require__(45131).CSSStyleDeclaration; -CSSOM.CSSKeyframeRule = __nccwpck_require__(97254).CSSKeyframeRule; -CSSOM.CSSKeyframesRule = __nccwpck_require__(16005).CSSKeyframesRule; -CSSOM.CSSValueExpression = __nccwpck_require__(75996).CSSValueExpression; -CSSOM.CSSDocumentRule = __nccwpck_require__(27455).CSSDocumentRule; +CSSOM.CSSStyleSheet = (__nccwpck_require__(62486).CSSStyleSheet); +CSSOM.CSSStyleRule = (__nccwpck_require__(4608).CSSStyleRule); +CSSOM.CSSImportRule = (__nccwpck_require__(49776).CSSImportRule); +CSSOM.CSSMediaRule = (__nccwpck_require__(96791).CSSMediaRule); +CSSOM.CSSSupportsRule = (__nccwpck_require__(27967).CSSSupportsRule); +CSSOM.CSSFontFaceRule = (__nccwpck_require__(33046).CSSFontFaceRule); +CSSOM.CSSHostRule = (__nccwpck_require__(57986).CSSHostRule); +CSSOM.CSSStyleDeclaration = (__nccwpck_require__(45131).CSSStyleDeclaration); +CSSOM.CSSKeyframeRule = (__nccwpck_require__(97254).CSSKeyframeRule); +CSSOM.CSSKeyframesRule = (__nccwpck_require__(16005).CSSKeyframesRule); +CSSOM.CSSValueExpression = (__nccwpck_require__(75996).CSSValueExpression); +CSSOM.CSSDocumentRule = (__nccwpck_require__(27455).CSSDocumentRule); ///CommonJS @@ -16148,7 +14544,7 @@ module.exports = implementedProperties; ********************************************************************/ -const namedColors = __nccwpck_require__(14947); +const namedColors = __nccwpck_require__(3800); const { hslToRgb } = __nccwpck_require__(90515); exports.TYPES = { @@ -18765,8 +17161,8 @@ module.exports = function getBasicPropertyDescriptor(name) { //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(24994).CSSRule, - MatcherList: __nccwpck_require__(81519).MatcherList + CSSRule: (__nccwpck_require__(24994).CSSRule), + MatcherList: (__nccwpck_require__(81519).MatcherList) }; ///CommonJS @@ -18811,8 +17207,8 @@ exports.CSSDocumentRule = CSSOM.CSSDocumentRule; //.CommonJS var CSSOM = { - CSSStyleDeclaration: __nccwpck_require__(21449).CSSStyleDeclaration, - CSSRule: __nccwpck_require__(24994).CSSRule + CSSStyleDeclaration: (__nccwpck_require__(21449).CSSStyleDeclaration), + CSSRule: (__nccwpck_require__(24994).CSSRule) }; ///CommonJS @@ -18854,7 +17250,7 @@ exports.CSSFontFaceRule = CSSOM.CSSFontFaceRule; //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(24994).CSSRule + CSSRule: (__nccwpck_require__(24994).CSSRule) }; ///CommonJS @@ -18898,9 +17294,9 @@ exports.CSSHostRule = CSSOM.CSSHostRule; //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(24994).CSSRule, - CSSStyleSheet: __nccwpck_require__(28050).CSSStyleSheet, - MediaList: __nccwpck_require__(77326).MediaList + CSSRule: (__nccwpck_require__(24994).CSSRule), + CSSStyleSheet: (__nccwpck_require__(28050).CSSStyleSheet), + MediaList: (__nccwpck_require__(77326).MediaList) }; ///CommonJS @@ -19037,8 +17433,8 @@ exports.CSSImportRule = CSSOM.CSSImportRule; //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(24994).CSSRule, - CSSStyleDeclaration: __nccwpck_require__(21449).CSSStyleDeclaration + CSSRule: (__nccwpck_require__(24994).CSSRule), + CSSStyleDeclaration: (__nccwpck_require__(21449).CSSStyleDeclaration) }; ///CommonJS @@ -19081,7 +17477,7 @@ exports.CSSKeyframeRule = CSSOM.CSSKeyframeRule; //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(24994).CSSRule + CSSRule: (__nccwpck_require__(24994).CSSRule) }; ///CommonJS @@ -19127,8 +17523,8 @@ exports.CSSKeyframesRule = CSSOM.CSSKeyframesRule; //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(24994).CSSRule, - MediaList: __nccwpck_require__(77326).MediaList + CSSRule: (__nccwpck_require__(24994).CSSRule), + MediaList: (__nccwpck_require__(77326).MediaList) }; ///CommonJS @@ -19369,7 +17765,7 @@ CSSOM.CSSStyleDeclaration.prototype = { //.CommonJS exports.CSSStyleDeclaration = CSSOM.CSSStyleDeclaration; -CSSOM.parse = __nccwpck_require__(10163).parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleDeclaration.js +CSSOM.parse = (__nccwpck_require__(10163).parse); // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleDeclaration.js ///CommonJS @@ -19380,8 +17776,8 @@ CSSOM.parse = __nccwpck_require__(10163).parse; // Cannot be included sooner due //.CommonJS var CSSOM = { - CSSStyleDeclaration: __nccwpck_require__(21449).CSSStyleDeclaration, - CSSRule: __nccwpck_require__(24994).CSSRule + CSSStyleDeclaration: (__nccwpck_require__(21449).CSSStyleDeclaration), + CSSRule: (__nccwpck_require__(24994).CSSRule) }; ///CommonJS @@ -19577,8 +17973,8 @@ exports.CSSStyleRule = CSSOM.CSSStyleRule; //.CommonJS var CSSOM = { - StyleSheet: __nccwpck_require__(98847).StyleSheet, - CSSStyleRule: __nccwpck_require__(57732).CSSStyleRule + StyleSheet: (__nccwpck_require__(98847).StyleSheet), + CSSStyleRule: (__nccwpck_require__(57732).CSSStyleRule) }; ///CommonJS @@ -19661,7 +18057,7 @@ CSSOM.CSSStyleSheet.prototype.toString = function() { //.CommonJS exports.CSSStyleSheet = CSSOM.CSSStyleSheet; -CSSOM.parse = __nccwpck_require__(10163).parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleSheet.js +CSSOM.parse = (__nccwpck_require__(10163).parse); // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleSheet.js ///CommonJS @@ -19672,7 +18068,7 @@ CSSOM.parse = __nccwpck_require__(10163).parse; // Cannot be included sooner due //.CommonJS var CSSOM = { - CSSRule: __nccwpck_require__(24994).CSSRule, + CSSRule: (__nccwpck_require__(24994).CSSRule), }; ///CommonJS @@ -19765,7 +18161,7 @@ exports.CSSValue = CSSOM.CSSValue; //.CommonJS var CSSOM = { - CSSValue: __nccwpck_require__(99880).CSSValue + CSSValue: (__nccwpck_require__(99880).CSSValue) }; ///CommonJS @@ -20277,13 +18673,13 @@ exports.StyleSheet = CSSOM.StyleSheet; //.CommonJS var CSSOM = { - CSSStyleSheet: __nccwpck_require__(28050).CSSStyleSheet, - CSSStyleRule: __nccwpck_require__(57732).CSSStyleRule, - CSSMediaRule: __nccwpck_require__(60365).CSSMediaRule, - CSSSupportsRule: __nccwpck_require__(92243).CSSSupportsRule, - CSSStyleDeclaration: __nccwpck_require__(21449).CSSStyleDeclaration, - CSSKeyframeRule: __nccwpck_require__(8308).CSSKeyframeRule, - CSSKeyframesRule: __nccwpck_require__(53702).CSSKeyframesRule + CSSStyleSheet: (__nccwpck_require__(28050).CSSStyleSheet), + CSSStyleRule: (__nccwpck_require__(57732).CSSStyleRule), + CSSMediaRule: (__nccwpck_require__(60365).CSSMediaRule), + CSSSupportsRule: (__nccwpck_require__(92243).CSSSupportsRule), + CSSStyleDeclaration: (__nccwpck_require__(21449).CSSStyleDeclaration), + CSSKeyframeRule: (__nccwpck_require__(8308).CSSKeyframeRule), + CSSKeyframesRule: (__nccwpck_require__(53702).CSSKeyframesRule) }; ///CommonJS @@ -20844,18 +19240,18 @@ CSSOM.parse = function parse(token) { //.CommonJS exports.parse = CSSOM.parse; // The following modules cannot be included sooner due to the mutual dependency with parse.js -CSSOM.CSSStyleSheet = __nccwpck_require__(28050).CSSStyleSheet; -CSSOM.CSSStyleRule = __nccwpck_require__(57732).CSSStyleRule; -CSSOM.CSSImportRule = __nccwpck_require__(15339).CSSImportRule; -CSSOM.CSSMediaRule = __nccwpck_require__(60365).CSSMediaRule; -CSSOM.CSSSupportsRule = __nccwpck_require__(92243).CSSSupportsRule; -CSSOM.CSSFontFaceRule = __nccwpck_require__(934).CSSFontFaceRule; -CSSOM.CSSHostRule = __nccwpck_require__(80576).CSSHostRule; -CSSOM.CSSStyleDeclaration = __nccwpck_require__(21449).CSSStyleDeclaration; -CSSOM.CSSKeyframeRule = __nccwpck_require__(8308).CSSKeyframeRule; -CSSOM.CSSKeyframesRule = __nccwpck_require__(53702).CSSKeyframesRule; -CSSOM.CSSValueExpression = __nccwpck_require__(56356).CSSValueExpression; -CSSOM.CSSDocumentRule = __nccwpck_require__(57775).CSSDocumentRule; +CSSOM.CSSStyleSheet = (__nccwpck_require__(28050).CSSStyleSheet); +CSSOM.CSSStyleRule = (__nccwpck_require__(57732).CSSStyleRule); +CSSOM.CSSImportRule = (__nccwpck_require__(15339).CSSImportRule); +CSSOM.CSSMediaRule = (__nccwpck_require__(60365).CSSMediaRule); +CSSOM.CSSSupportsRule = (__nccwpck_require__(92243).CSSSupportsRule); +CSSOM.CSSFontFaceRule = (__nccwpck_require__(934).CSSFontFaceRule); +CSSOM.CSSHostRule = (__nccwpck_require__(80576).CSSHostRule); +CSSOM.CSSStyleDeclaration = (__nccwpck_require__(21449).CSSStyleDeclaration); +CSSOM.CSSKeyframeRule = (__nccwpck_require__(8308).CSSKeyframeRule); +CSSOM.CSSKeyframesRule = (__nccwpck_require__(53702).CSSKeyframesRule); +CSSOM.CSSValueExpression = (__nccwpck_require__(56356).CSSValueExpression); +CSSOM.CSSDocumentRule = (__nccwpck_require__(57775).CSSDocumentRule); ///CommonJS @@ -42027,8 +40423,8 @@ if (typeof process === 'undefined' || process.type === 'renderer' || process.bro * Module dependencies. */ -const tty = __nccwpck_require__(33867); -const util = __nccwpck_require__(31669); +const tty = __nccwpck_require__(76224); +const util = __nccwpck_require__(73837); /** * This is the Node.js implementation of `debug()`. @@ -42293,25234 +40689,22028 @@ formatters.O = function (v) { /***/ 49458: /***/ (function(module) { -;(function (globalScope) { - 'use strict'; - - - /* - * decimal.js v10.2.1 - * An arbitrary-precision Decimal type for JavaScript. - * https://github.com/MikeMcl/decimal.js - * Copyright (c) 2020 Michael Mclaughlin - * MIT Licence - */ - - - // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ // - - - // The maximum exponent magnitude. - // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`. - var EXP_LIMIT = 9e15, // 0 to 9e15 - - // The limit on the value of `precision`, and on the value of the first argument to - // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`. - MAX_DIGITS = 1e9, // 0 to 1e9 - - // Base conversion alphabet. - NUMERALS = '0123456789abcdef', - - // The natural logarithm of 10 (1025 digits). - LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058', - - // Pi (1025 digits). - PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789', - - - // The initial configuration properties of the Decimal constructor. - DEFAULTS = { - - // These values must be integers within the stated ranges (inclusive). - // Most of these values can be changed at run-time using the `Decimal.config` method. - - // The maximum number of significant digits of the result of a calculation or base conversion. - // E.g. `Decimal.config({ precision: 20 });` - precision: 20, // 1 to MAX_DIGITS - - // The rounding mode used when rounding to `precision`. - // - // ROUND_UP 0 Away from zero. - // ROUND_DOWN 1 Towards zero. - // ROUND_CEIL 2 Towards +Infinity. - // ROUND_FLOOR 3 Towards -Infinity. - // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up. - // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. - // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. - // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. - // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. - // - // E.g. - // `Decimal.rounding = 4;` - // `Decimal.rounding = Decimal.ROUND_HALF_UP;` - rounding: 4, // 0 to 8 - - // The modulo mode used when calculating the modulus: a mod n. - // The quotient (q = a / n) is calculated according to the corresponding rounding mode. - // The remainder (r) is calculated as: r = a - n * q. - // - // UP 0 The remainder is positive if the dividend is negative, else is negative. - // DOWN 1 The remainder has the same sign as the dividend (JavaScript %). - // FLOOR 3 The remainder has the same sign as the divisor (Python %). - // HALF_EVEN 6 The IEEE 754 remainder function. - // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive. - // - // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian - // division (9) are commonly used for the modulus operation. The other rounding modes can also - // be used, but they may not give useful results. - modulo: 1, // 0 to 9 - - // The exponent value at and beneath which `toString` returns exponential notation. - // JavaScript numbers: -7 - toExpNeg: -7, // 0 to -EXP_LIMIT - - // The exponent value at and above which `toString` returns exponential notation. - // JavaScript numbers: 21 - toExpPos: 21, // 0 to EXP_LIMIT - - // The minimum exponent value, beneath which underflow to zero occurs. - // JavaScript numbers: -324 (5e-324) - minE: -EXP_LIMIT, // -1 to -EXP_LIMIT - - // The maximum exponent value, above which overflow to Infinity occurs. - // JavaScript numbers: 308 (1.7976931348623157e+308) - maxE: EXP_LIMIT, // 1 to EXP_LIMIT - - // Whether to use cryptographically-secure random number generation, if available. - crypto: false // true/false - }, - - - // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- // - - - Decimal, inexact, noConflict, quadrant, - external = true, - - decimalError = '[DecimalError] ', - invalidArgument = decimalError + 'Invalid argument: ', - precisionLimitExceeded = decimalError + 'Precision limit exceeded', - cryptoUnavailable = decimalError + 'crypto unavailable', - - mathfloor = Math.floor, - mathpow = Math.pow, - - isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i, - isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i, - isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i, - isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, - - BASE = 1e7, - LOG_BASE = 7, - MAX_SAFE_INTEGER = 9007199254740991, - - LN10_PRECISION = LN10.length - 1, - PI_PRECISION = PI.length - 1, - - // Decimal.prototype object - P = { name: '[object Decimal]' }; - - - // Decimal prototype methods - - - /* - * absoluteValue abs - * ceil - * comparedTo cmp - * cosine cos - * cubeRoot cbrt - * decimalPlaces dp - * dividedBy div - * dividedToIntegerBy divToInt - * equals eq - * floor - * greaterThan gt - * greaterThanOrEqualTo gte - * hyperbolicCosine cosh - * hyperbolicSine sinh - * hyperbolicTangent tanh - * inverseCosine acos - * inverseHyperbolicCosine acosh - * inverseHyperbolicSine asinh - * inverseHyperbolicTangent atanh - * inverseSine asin - * inverseTangent atan - * isFinite - * isInteger isInt - * isNaN - * isNegative isNeg - * isPositive isPos - * isZero - * lessThan lt - * lessThanOrEqualTo lte - * logarithm log - * [maximum] [max] - * [minimum] [min] - * minus sub - * modulo mod - * naturalExponential exp - * naturalLogarithm ln - * negated neg - * plus add - * precision sd - * round - * sine sin - * squareRoot sqrt - * tangent tan - * times mul - * toBinary - * toDecimalPlaces toDP - * toExponential - * toFixed - * toFraction - * toHexadecimal toHex - * toNearest - * toNumber - * toOctal - * toPower pow - * toPrecision - * toSignificantDigits toSD - * toString - * truncated trunc - * valueOf toJSON - */ - - - /* - * Return a new Decimal whose value is the absolute value of this Decimal. - * - */ - P.absoluteValue = P.abs = function () { - var x = new this.constructor(this); - if (x.s < 0) x.s = 1; - return finalise(x); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the - * direction of positive Infinity. - * - */ - P.ceil = function () { - return finalise(new this.constructor(this), this.e + 1, 2); - }; - - - /* - * Return - * 1 if the value of this Decimal is greater than the value of `y`, - * -1 if the value of this Decimal is less than the value of `y`, - * 0 if they have the same value, - * NaN if the value of either Decimal is NaN. - * - */ - P.comparedTo = P.cmp = function (y) { - var i, j, xdL, ydL, - x = this, - xd = x.d, - yd = (y = new x.constructor(y)).d, - xs = x.s, - ys = y.s; - - // Either NaN or ±Infinity? - if (!xd || !yd) { - return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; - } - - // Either zero? - if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; - - // Signs differ? - if (xs !== ys) return xs; - - // Compare exponents. - if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; - - xdL = xd.length; - ydL = yd.length; - - // Compare digit by digit. - for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { - if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; - } - - // Compare lengths. - return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; - }; - - - /* - * Return a new Decimal whose value is the cosine of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * cos(0) = 1 - * cos(-0) = 1 - * cos(Infinity) = NaN - * cos(-Infinity) = NaN - * cos(NaN) = NaN - * - */ - P.cosine = P.cos = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.d) return new Ctor(NaN); - - // cos(0) = cos(-0) = 1 - if (!x.d[0]) return new Ctor(1); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; - Ctor.rounding = 1; - - x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); - }; - - - /* - * - * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * cbrt(0) = 0 - * cbrt(-0) = -0 - * cbrt(1) = 1 - * cbrt(-1) = -1 - * cbrt(N) = N - * cbrt(-I) = -I - * cbrt(I) = I - * - * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3)) - * - */ - P.cubeRoot = P.cbrt = function () { - var e, m, n, r, rep, s, sd, t, t3, t3plusx, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - external = false; - - // Initial estimate. - s = x.s * mathpow(x.s * x, 1 / 3); - - // Math.cbrt underflow/overflow? - // Pass x to Math.pow as integer, then adjust the exponent of the result. - if (!s || Math.abs(s) == 1 / 0) { - n = digitsToString(x.d); - e = x.e; - - // Adjust n exponent so it is a multiple of 3 away from x exponent. - if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); - s = mathpow(n, 1 / 3); - - // Rarely, e may be one less than the result exponent value. - e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); - - if (s == 1 / 0) { - n = '5e' + e; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf('e') + 1) + e; - } - - r = new Ctor(n); - r.s = x.s; - } else { - r = new Ctor(s.toString()); - } - - sd = (e = Ctor.precision) + 3; - - // Halley's method. - // TODO? Compare Newton's method. - for (;;) { - t = r; - t3 = t.times(t).times(t); - t3plusx = t3.plus(x); - r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); - - // TODO? Replace with for-loop and checkRoundingDigits. - if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { - n = n.slice(sd - 3, sd + 1); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 - // , i.e. approaching a rounding boundary, continue the iteration. - if (n == '9999' || !rep && n == '4999') { - - // On the first iteration only, check to see if rounding up gives the exact result as the - // nines may infinitely repeat. - if (!rep) { - finalise(t, e + 1, 0); - - if (t.times(t).times(t).eq(x)) { - r = t; - break; - } - } - - sd += 4; - rep = 1; - } else { - - // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. - // If not, then there are further digits and m will be truthy. - if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - - // Truncate to the first rounding digit. - finalise(r, e + 1, 1); - m = !r.times(r).times(r).eq(x); - } - - break; - } - } - } - - external = true; - - return finalise(r, e, Ctor.rounding, m); - }; - - - /* - * Return the number of decimal places of the value of this Decimal. - * - */ - P.decimalPlaces = P.dp = function () { - var w, - d = this.d, - n = NaN; - - if (d) { - w = d.length - 1; - n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; - - // Subtract the number of trailing zeros of the last word. - w = d[w]; - if (w) for (; w % 10 == 0; w /= 10) n--; - if (n < 0) n = 0; - } - - return n; - }; - - - /* - * n / 0 = I - * n / N = N - * n / I = 0 - * 0 / n = 0 - * 0 / 0 = N - * 0 / N = N - * 0 / I = 0 - * N / n = N - * N / 0 = N - * N / N = N - * N / I = N - * I / n = I - * I / 0 = I - * I / N = N - * I / I = N - * - * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - */ - P.dividedBy = P.div = function (y) { - return divide(this, new this.constructor(y)); - }; - - - /* - * Return a new Decimal whose value is the integer part of dividing the value of this Decimal - * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`. - * - */ - P.dividedToIntegerBy = P.divToInt = function (y) { - var x = this, - Ctor = x.constructor; - return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); - }; - - - /* - * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. - * - */ - P.equals = P.eq = function (y) { - return this.cmp(y) === 0; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the - * direction of negative Infinity. - * - */ - P.floor = function () { - return finalise(new this.constructor(this), this.e + 1, 3); - }; - - - /* - * Return true if the value of this Decimal is greater than the value of `y`, otherwise return - * false. - * - */ - P.greaterThan = P.gt = function (y) { - return this.cmp(y) > 0; - }; - - - /* - * Return true if the value of this Decimal is greater than or equal to the value of `y`, - * otherwise return false. - * - */ - P.greaterThanOrEqualTo = P.gte = function (y) { - var k = this.cmp(y); - return k == 1 || k === 0; - }; - - - /* - * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [1, Infinity] - * - * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ... - * - * cosh(0) = 1 - * cosh(-0) = 1 - * cosh(Infinity) = Infinity - * cosh(-Infinity) = Infinity - * cosh(NaN) = NaN - * - * x time taken (ms) result - * 1000 9 9.8503555700852349694e+433 - * 10000 25 4.4034091128314607936e+4342 - * 100000 171 1.4033316802130615897e+43429 - * 1000000 3817 1.5166076984010437725e+434294 - * 10000000 abandoned after 2 minute wait - * - * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x)) - * - */ - P.hyperbolicCosine = P.cosh = function () { - var k, n, pr, rm, len, - x = this, - Ctor = x.constructor, - one = new Ctor(1); - - if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); - if (x.isZero()) return one; - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; - Ctor.rounding = 1; - len = x.d.length; - - // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 - // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) - - // Estimate the optimum number of times to use the argument reduction. - // TODO? Estimation reused from cosine() and may not be optimal here. - if (len < 32) { - k = Math.ceil(len / 3); - n = (1 / tinyPow(4, k)).toString(); - } else { - k = 16; - n = '2.3283064365386962890625e-10'; - } - - x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); - - // Reverse argument reduction - var cosh2_x, - i = k, - d8 = new Ctor(8); - for (; i--;) { - cosh2_x = x.times(x); - x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); - } - - return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); - }; - - - /* - * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ... - * - * sinh(0) = 0 - * sinh(-0) = -0 - * sinh(Infinity) = Infinity - * sinh(-Infinity) = -Infinity - * sinh(NaN) = NaN - * - * x time taken (ms) - * 10 2 ms - * 100 5 ms - * 1000 14 ms - * 10000 82 ms - * 100000 886 ms 1.4033316802130615897e+43429 - * 200000 2613 ms - * 300000 5407 ms - * 400000 8824 ms - * 500000 13026 ms 8.7080643612718084129e+217146 - * 1000000 48543 ms - * - * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x)) - * - */ - P.hyperbolicSine = P.sinh = function () { - var k, pr, rm, len, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; - Ctor.rounding = 1; - len = x.d.length; - - if (len < 3) { - x = taylorSeries(Ctor, 2, x, x, true); - } else { - - // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) - // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) - // 3 multiplications and 1 addition - - // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) - // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) - // 4 multiplications and 2 additions - - // Estimate the optimum number of times to use the argument reduction. - k = 1.4 * Math.sqrt(len); - k = k > 16 ? 16 : k | 0; - - x = x.times(1 / tinyPow(5, k)); - x = taylorSeries(Ctor, 2, x, x, true); - - // Reverse argument reduction - var sinh2_x, - d5 = new Ctor(5), - d16 = new Ctor(16), - d20 = new Ctor(20); - for (; k--;) { - sinh2_x = x.times(x); - x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); - } - } - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(x, pr, rm, true); - }; - - - /* - * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * tanh(x) = sinh(x) / cosh(x) - * - * tanh(0) = 0 - * tanh(-0) = -0 - * tanh(Infinity) = 1 - * tanh(-Infinity) = -1 - * tanh(NaN) = NaN - * - */ - P.hyperbolicTangent = P.tanh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(x.s); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 7; - Ctor.rounding = 1; - - return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); - }; - - - /* - * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of - * this Decimal. - * - * Domain: [-1, 1] - * Range: [0, pi] - * - * acos(x) = pi/2 - asin(x) - * - * acos(0) = pi/2 - * acos(-0) = pi/2 - * acos(1) = 0 - * acos(-1) = pi - * acos(1/2) = pi/3 - * acos(-1/2) = 2*pi/3 - * acos(|x| > 1) = NaN - * acos(NaN) = NaN - * - */ - P.inverseCosine = P.acos = function () { - var halfPi, - x = this, - Ctor = x.constructor, - k = x.abs().cmp(1), - pr = Ctor.precision, - rm = Ctor.rounding; - - if (k !== -1) { - return k === 0 - // |x| is 1 - ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) - // |x| > 1 or x is NaN - : new Ctor(NaN); - } - - if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); - - // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 - - Ctor.precision = pr + 6; - Ctor.rounding = 1; - - x = x.asin(); - halfPi = getPi(Ctor, pr + 4, rm).times(0.5); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return halfPi.minus(x); - }; - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the - * value of this Decimal. - * - * Domain: [1, Infinity] - * Range: [0, Infinity] - * - * acosh(x) = ln(x + sqrt(x^2 - 1)) - * - * acosh(x < 1) = NaN - * acosh(NaN) = NaN - * acosh(Infinity) = Infinity - * acosh(-Infinity) = NaN - * acosh(0) = NaN - * acosh(-0) = NaN - * acosh(1) = 0 - * acosh(-1) = NaN - * - */ - P.inverseHyperbolicCosine = P.acosh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); - if (!x.isFinite()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; - Ctor.rounding = 1; - external = false; - - x = x.times(x).minus(1).sqrt().plus(x); - - external = true; - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.ln(); - }; - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value - * of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * asinh(x) = ln(x + sqrt(x^2 + 1)) - * - * asinh(NaN) = NaN - * asinh(Infinity) = Infinity - * asinh(-Infinity) = -Infinity - * asinh(0) = 0 - * asinh(-0) = -0 - * - */ - P.inverseHyperbolicSine = P.asinh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; - Ctor.rounding = 1; - external = false; - - x = x.times(x).plus(1).sqrt().plus(x); - - external = true; - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.ln(); - }; - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the - * value of this Decimal. - * - * Domain: [-1, 1] - * Range: [-Infinity, Infinity] - * - * atanh(x) = 0.5 * ln((1 + x) / (1 - x)) - * - * atanh(|x| > 1) = NaN - * atanh(NaN) = NaN - * atanh(Infinity) = NaN - * atanh(-Infinity) = NaN - * atanh(0) = 0 - * atanh(-0) = -0 - * atanh(1) = Infinity - * atanh(-1) = -Infinity - * - */ - P.inverseHyperbolicTangent = P.atanh = function () { - var pr, rm, wpr, xsd, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); - - pr = Ctor.precision; - rm = Ctor.rounding; - xsd = x.sd(); - - if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); - - Ctor.precision = wpr = xsd - x.e; - - x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); - - Ctor.precision = pr + 4; - Ctor.rounding = 1; - - x = x.ln(); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.times(0.5); - }; - - - /* - * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi/2, pi/2] - * - * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2))) - * - * asin(0) = 0 - * asin(-0) = -0 - * asin(1/2) = pi/6 - * asin(-1/2) = -pi/6 - * asin(1) = pi/2 - * asin(-1) = -pi/2 - * asin(|x| > 1) = NaN - * asin(NaN) = NaN - * - * TODO? Compare performance of Taylor series. - * - */ - P.inverseSine = P.asin = function () { - var halfPi, k, - pr, rm, - x = this, - Ctor = x.constructor; - - if (x.isZero()) return new Ctor(x); - - k = x.abs().cmp(1); - pr = Ctor.precision; - rm = Ctor.rounding; - - if (k !== -1) { - - // |x| is 1 - if (k === 0) { - halfPi = getPi(Ctor, pr + 4, rm).times(0.5); - halfPi.s = x.s; - return halfPi; - } - - // |x| > 1 or x is NaN - return new Ctor(NaN); - } - - // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 - - Ctor.precision = pr + 6; - Ctor.rounding = 1; - - x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.times(2); - }; - - - /* - * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value - * of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi/2, pi/2] - * - * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... - * - * atan(0) = 0 - * atan(-0) = -0 - * atan(1) = pi/4 - * atan(-1) = -pi/4 - * atan(Infinity) = pi/2 - * atan(-Infinity) = -pi/2 - * atan(NaN) = NaN - * - */ - P.inverseTangent = P.atan = function () { - var i, j, k, n, px, t, r, wpr, x2, - x = this, - Ctor = x.constructor, - pr = Ctor.precision, - rm = Ctor.rounding; - - if (!x.isFinite()) { - if (!x.s) return new Ctor(NaN); - if (pr + 4 <= PI_PRECISION) { - r = getPi(Ctor, pr + 4, rm).times(0.5); - r.s = x.s; - return r; - } - } else if (x.isZero()) { - return new Ctor(x); - } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { - r = getPi(Ctor, pr + 4, rm).times(0.25); - r.s = x.s; - return r; - } - - Ctor.precision = wpr = pr + 10; - Ctor.rounding = 1; - - // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); - - // Argument reduction - // Ensure |x| < 0.42 - // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) - - k = Math.min(28, wpr / LOG_BASE + 2 | 0); - - for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); - - external = false; - - j = Math.ceil(wpr / LOG_BASE); - n = 1; - x2 = x.times(x); - r = new Ctor(x); - px = x; - - // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... - for (; i !== -1;) { - px = px.times(x2); - t = r.minus(px.div(n += 2)); - - px = px.times(x2); - r = t.plus(px.div(n += 2)); - - if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); - } - - if (k) r = r.times(2 << (k - 1)); - - external = true; - - return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); - }; - - - /* - * Return true if the value of this Decimal is a finite number, otherwise return false. - * - */ - P.isFinite = function () { - return !!this.d; - }; - - - /* - * Return true if the value of this Decimal is an integer, otherwise return false. - * - */ - P.isInteger = P.isInt = function () { - return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; - }; - - - /* - * Return true if the value of this Decimal is NaN, otherwise return false. - * - */ - P.isNaN = function () { - return !this.s; - }; - - - /* - * Return true if the value of this Decimal is negative, otherwise return false. - * - */ - P.isNegative = P.isNeg = function () { - return this.s < 0; - }; - - - /* - * Return true if the value of this Decimal is positive, otherwise return false. - * - */ - P.isPositive = P.isPos = function () { - return this.s > 0; - }; - - - /* - * Return true if the value of this Decimal is 0 or -0, otherwise return false. - * - */ - P.isZero = function () { - return !!this.d && this.d[0] === 0; - }; - - - /* - * Return true if the value of this Decimal is less than `y`, otherwise return false. - * - */ - P.lessThan = P.lt = function (y) { - return this.cmp(y) < 0; - }; - - - /* - * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. - * - */ - P.lessThanOrEqualTo = P.lte = function (y) { - return this.cmp(y) < 1; - }; - - - /* - * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * If no base is specified, return log[10](arg). - * - * log[base](arg) = ln(arg) / ln(base) - * - * The result will always be correctly rounded if the base of the log is 10, and 'almost always' - * otherwise: - * - * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen - * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error - * between the result and the correctly rounded result will be one ulp (unit in the last place). - * - * log[-b](a) = NaN - * log[0](a) = NaN - * log[1](a) = NaN - * log[NaN](a) = NaN - * log[Infinity](a) = NaN - * log[b](0) = -Infinity - * log[b](-0) = -Infinity - * log[b](-a) = NaN - * log[b](1) = 0 - * log[b](Infinity) = Infinity - * log[b](NaN) = NaN - * - * [base] {number|string|Decimal} The base of the logarithm. - * - */ - P.logarithm = P.log = function (base) { - var isBase10, d, denominator, k, inf, num, sd, r, - arg = this, - Ctor = arg.constructor, - pr = Ctor.precision, - rm = Ctor.rounding, - guard = 5; - - // Default base is 10. - if (base == null) { - base = new Ctor(10); - isBase10 = true; - } else { - base = new Ctor(base); - d = base.d; - - // Return NaN if base is negative, or non-finite, or is 0 or 1. - if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); - - isBase10 = base.eq(10); - } - - d = arg.d; - - // Is arg negative, non-finite, 0 or 1? - if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { - return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); - } - - // The result will have a non-terminating decimal expansion if base is 10 and arg is not an - // integer power of 10. - if (isBase10) { - if (d.length > 1) { - inf = true; - } else { - for (k = d[0]; k % 10 === 0;) k /= 10; - inf = k !== 1; - } - } - - external = false; - sd = pr + guard; - num = naturalLogarithm(arg, sd); - denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); - - // The result will have 5 rounding digits. - r = divide(num, denominator, sd, 1); - - // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, - // calculate 10 further digits. - // - // If the result is known to have an infinite decimal expansion, repeat this until it is clear - // that the result is above or below the boundary. Otherwise, if after calculating the 10 - // further digits, the last 14 are nines, round up and assume the result is exact. - // Also assume the result is exact if the last 14 are zero. - // - // Example of a result that will be incorrectly rounded: - // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... - // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it - // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so - // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal - // place is still 2.6. - if (checkRoundingDigits(r.d, k = pr, rm)) { - - do { - sd += 10; - num = naturalLogarithm(arg, sd); - denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); - r = divide(num, denominator, sd, 1); - - if (!inf) { - - // Check for 14 nines from the 2nd rounding digit, as the first may be 4. - if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { - r = finalise(r, pr + 1, 0); - } - - break; - } - } while (checkRoundingDigits(r.d, k += 10, rm)); - } - - external = true; - - return finalise(r, pr, rm); - }; - - - /* - * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal. - * - * arguments {number|string|Decimal} - * - P.max = function () { - Array.prototype.push.call(arguments, this); - return maxOrMin(this.constructor, arguments, 'lt'); - }; - */ - - - /* - * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal. - * - * arguments {number|string|Decimal} - * - P.min = function () { - Array.prototype.push.call(arguments, this); - return maxOrMin(this.constructor, arguments, 'gt'); - }; - */ - - - /* - * n - 0 = n - * n - N = N - * n - I = -I - * 0 - n = -n - * 0 - 0 = 0 - * 0 - N = N - * 0 - I = -I - * N - n = N - * N - 0 = N - * N - N = N - * N - I = N - * I - n = I - * I - 0 = I - * I - N = N - * I - I = N - * - * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ - P.minus = P.sub = function (y) { - var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // If either is not finite... - if (!x.d || !y.d) { - - // Return NaN if either is NaN. - if (!x.s || !y.s) y = new Ctor(NaN); - - // Return y negated if x is finite and y is ±Infinity. - else if (x.d) y.s = -y.s; - - // Return x if y is finite and x is ±Infinity. - // Return x if both are ±Infinity with different signs. - // Return NaN if both are ±Infinity with the same sign. - else y = new Ctor(y.d || x.s !== y.s ? x : NaN); - - return y; - } - - // If signs differ... - if (x.s != y.s) { - y.s = -y.s; - return x.plus(y); - } - - xd = x.d; - yd = y.d; - pr = Ctor.precision; - rm = Ctor.rounding; - - // If either is zero... - if (!xd[0] || !yd[0]) { - - // Return y negated if x is zero and y is non-zero. - if (yd[0]) y.s = -y.s; - - // Return x if y is zero and x is non-zero. - else if (xd[0]) y = new Ctor(x); - - // Return zero if both are zero. - // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. - else return new Ctor(rm === 3 ? -0 : 0); - - return external ? finalise(y, pr, rm) : y; - } - - // x and y are finite, non-zero numbers with the same sign. - - // Calculate base 1e7 exponents. - e = mathfloor(y.e / LOG_BASE); - xe = mathfloor(x.e / LOG_BASE); - - xd = xd.slice(); - k = xe - e; - - // If base 1e7 exponents differ... - if (k) { - xLTy = k < 0; - - if (xLTy) { - d = xd; - k = -k; - len = yd.length; - } else { - d = yd; - e = xe; - len = xd.length; - } - - // Numbers with massively different exponents would result in a very high number of - // zeros needing to be prepended, but this can be avoided while still ensuring correct - // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. - i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; - - if (k > i) { - k = i; - d.length = 1; - } - - // Prepend zeros to equalise exponents. - d.reverse(); - for (i = k; i--;) d.push(0); - d.reverse(); - - // Base 1e7 exponents equal. - } else { - - // Check digits to determine which is the bigger number. - - i = xd.length; - len = yd.length; - xLTy = i < len; - if (xLTy) len = i; - - for (i = 0; i < len; i++) { - if (xd[i] != yd[i]) { - xLTy = xd[i] < yd[i]; - break; - } - } - - k = 0; - } - - if (xLTy) { - d = xd; - xd = yd; - yd = d; - y.s = -y.s; - } - - len = xd.length; - - // Append zeros to `xd` if shorter. - // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. - for (i = yd.length - len; i > 0; --i) xd[len++] = 0; - - // Subtract yd from xd. - for (i = yd.length; i > k;) { - - if (xd[--i] < yd[i]) { - for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; - --xd[j]; - xd[i] += BASE; - } - - xd[i] -= yd[i]; - } - - // Remove trailing zeros. - for (; xd[--len] === 0;) xd.pop(); - - // Remove leading zeros and adjust exponent accordingly. - for (; xd[0] === 0; xd.shift()) --e; - - // Zero? - if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); - - y.d = xd; - y.e = getBase10Exponent(xd, e); - - return external ? finalise(y, pr, rm) : y; - }; - - - /* - * n % 0 = N - * n % N = N - * n % I = n - * 0 % n = 0 - * -0 % n = -0 - * 0 % 0 = N - * 0 % N = N - * 0 % I = 0 - * N % n = N - * N % 0 = N - * N % N = N - * N % I = N - * I % n = N - * I % 0 = N - * I % N = N - * I % I = N - * - * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * The result depends on the modulo mode. - * - */ - P.modulo = P.mod = function (y) { - var q, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. - if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); - - // Return x if y is ±Infinity or x is ±0. - if (!y.d || x.d && !x.d[0]) { - return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); - } - - // Prevent rounding of intermediate calculations. - external = false; - - if (Ctor.modulo == 9) { - - // Euclidian division: q = sign(y) * floor(x / abs(y)) - // result = x - q * y where 0 <= result < abs(y) - q = divide(x, y.abs(), 0, 3, 1); - q.s *= y.s; - } else { - q = divide(x, y, 0, Ctor.modulo, 1); - } - - q = q.times(y); - - external = true; - - return x.minus(q); - }; - - - /* - * Return a new Decimal whose value is the natural exponential of the value of this Decimal, - * i.e. the base e raised to the power the value of this Decimal, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ - P.naturalExponential = P.exp = function () { - return naturalExponential(this); - }; - - - /* - * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, - * rounded to `precision` significant digits using rounding mode `rounding`. - * - */ - P.naturalLogarithm = P.ln = function () { - return naturalLogarithm(this); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by - * -1. - * - */ - P.negated = P.neg = function () { - var x = new this.constructor(this); - x.s = -x.s; - return finalise(x); - }; - - - /* - * n + 0 = n - * n + N = N - * n + I = I - * 0 + n = n - * 0 + 0 = 0 - * 0 + N = N - * 0 + I = I - * N + n = N - * N + 0 = N - * N + N = N - * N + I = N - * I + n = I - * I + 0 = I - * I + N = N - * I + I = I - * - * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ - P.plus = P.add = function (y) { - var carry, d, e, i, k, len, pr, rm, xd, yd, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // If either is not finite... - if (!x.d || !y.d) { - - // Return NaN if either is NaN. - if (!x.s || !y.s) y = new Ctor(NaN); - - // Return x if y is finite and x is ±Infinity. - // Return x if both are ±Infinity with the same sign. - // Return NaN if both are ±Infinity with different signs. - // Return y if x is finite and y is ±Infinity. - else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); - - return y; - } - - // If signs differ... - if (x.s != y.s) { - y.s = -y.s; - return x.minus(y); - } - - xd = x.d; - yd = y.d; - pr = Ctor.precision; - rm = Ctor.rounding; - - // If either is zero... - if (!xd[0] || !yd[0]) { - - // Return x if y is zero. - // Return y if y is non-zero. - if (!yd[0]) y = new Ctor(x); - - return external ? finalise(y, pr, rm) : y; - } - - // x and y are finite, non-zero numbers with the same sign. - - // Calculate base 1e7 exponents. - k = mathfloor(x.e / LOG_BASE); - e = mathfloor(y.e / LOG_BASE); - - xd = xd.slice(); - i = k - e; - - // If base 1e7 exponents differ... - if (i) { - - if (i < 0) { - d = xd; - i = -i; - len = yd.length; - } else { - d = yd; - e = k; - len = xd.length; - } - - // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. - k = Math.ceil(pr / LOG_BASE); - len = k > len ? k + 1 : len + 1; - - if (i > len) { - i = len; - d.length = 1; - } - - // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. - d.reverse(); - for (; i--;) d.push(0); - d.reverse(); - } - - len = xd.length; - i = yd.length; - - // If yd is longer than xd, swap xd and yd so xd points to the longer array. - if (len - i < 0) { - i = len; - d = yd; - yd = xd; - xd = d; - } - - // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. - for (carry = 0; i;) { - carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; - xd[i] %= BASE; - } - - if (carry) { - xd.unshift(carry); - ++e; - } - - // Remove trailing zeros. - // No need to check for zero, as +x + +y != 0 && -x + -y != 0 - for (len = xd.length; xd[--len] == 0;) xd.pop(); - - y.d = xd; - y.e = getBase10Exponent(xd, e); - - return external ? finalise(y, pr, rm) : y; - }; - - - /* - * Return the number of significant digits of the value of this Decimal. - * - * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. - * - */ - P.precision = P.sd = function (z) { - var k, - x = this; - - if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); - - if (x.d) { - k = getPrecision(x.d); - if (z && x.e + 1 > k) k = x.e + 1; - } else { - k = NaN; - } - - return k; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using - * rounding mode `rounding`. - * - */ - P.round = function () { - var x = this, - Ctor = x.constructor; - - return finalise(new Ctor(x), x.e + 1, Ctor.rounding); - }; - - - /* - * Return a new Decimal whose value is the sine of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * sin(x) = x - x^3/3! + x^5/5! - ... - * - * sin(0) = 0 - * sin(-0) = -0 - * sin(Infinity) = NaN - * sin(-Infinity) = NaN - * sin(NaN) = NaN - * - */ - P.sine = P.sin = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; - Ctor.rounding = 1; - - x = sine(Ctor, toLessThanHalfPi(Ctor, x)); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); - }; - - - /* - * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * sqrt(-n) = N - * sqrt(N) = N - * sqrt(-I) = N - * sqrt(I) = I - * sqrt(0) = 0 - * sqrt(-0) = -0 - * - */ - P.squareRoot = P.sqrt = function () { - var m, n, sd, r, rep, t, - x = this, - d = x.d, - e = x.e, - s = x.s, - Ctor = x.constructor; - - // Negative/NaN/Infinity/zero? - if (s !== 1 || !d || !d[0]) { - return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); - } - - external = false; - - // Initial estimate. - s = Math.sqrt(+x); - - // Math.sqrt underflow/overflow? - // Pass x to Math.sqrt as integer, then adjust the exponent of the result. - if (s == 0 || s == 1 / 0) { - n = digitsToString(d); - - if ((n.length + e) % 2 == 0) n += '0'; - s = Math.sqrt(n); - e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); - - if (s == 1 / 0) { - n = '5e' + e; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf('e') + 1) + e; - } - - r = new Ctor(n); - } else { - r = new Ctor(s.toString()); - } - - sd = (e = Ctor.precision) + 3; - - // Newton-Raphson iteration. - for (;;) { - t = r; - r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); - - // TODO? Replace with for-loop and checkRoundingDigits. - if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { - n = n.slice(sd - 3, sd + 1); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or - // 4999, i.e. approaching a rounding boundary, continue the iteration. - if (n == '9999' || !rep && n == '4999') { - - // On the first iteration only, check to see if rounding up gives the exact result as the - // nines may infinitely repeat. - if (!rep) { - finalise(t, e + 1, 0); - - if (t.times(t).eq(x)) { - r = t; - break; - } - } - - sd += 4; - rep = 1; - } else { - - // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. - // If not, then there are further digits and m will be truthy. - if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - - // Truncate to the first rounding digit. - finalise(r, e + 1, 1); - m = !r.times(r).eq(x); - } - - break; - } - } - } - - external = true; - - return finalise(r, e, Ctor.rounding, m); - }; - - - /* - * Return a new Decimal whose value is the tangent of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * tan(0) = 0 - * tan(-0) = -0 - * tan(Infinity) = NaN - * tan(-Infinity) = NaN - * tan(NaN) = NaN - * - */ - P.tangent = P.tan = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 10; - Ctor.rounding = 1; - - x = x.sin(); - x.s = 1; - x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); - }; - - - /* - * n * 0 = 0 - * n * N = N - * n * I = I - * 0 * n = 0 - * 0 * 0 = 0 - * 0 * N = N - * 0 * I = N - * N * n = N - * N * 0 = N - * N * N = N - * N * I = N - * I * n = I - * I * 0 = N - * I * N = N - * I * I = I - * - * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - */ - P.times = P.mul = function (y) { - var carry, e, i, k, r, rL, t, xdL, ydL, - x = this, - Ctor = x.constructor, - xd = x.d, - yd = (y = new Ctor(y)).d; - - y.s *= x.s; - - // If either is NaN, ±Infinity or ±0... - if (!xd || !xd[0] || !yd || !yd[0]) { - - return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd - - // Return NaN if either is NaN. - // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. - ? NaN - - // Return ±Infinity if either is ±Infinity. - // Return ±0 if either is ±0. - : !xd || !yd ? y.s / 0 : y.s * 0); - } - - e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); - xdL = xd.length; - ydL = yd.length; - - // Ensure xd points to the longer array. - if (xdL < ydL) { - r = xd; - xd = yd; - yd = r; - rL = xdL; - xdL = ydL; - ydL = rL; - } - - // Initialise the result array with zeros. - r = []; - rL = xdL + ydL; - for (i = rL; i--;) r.push(0); - - // Multiply! - for (i = ydL; --i >= 0;) { - carry = 0; - for (k = xdL + i; k > i;) { - t = r[k] + yd[i] * xd[k - i - 1] + carry; - r[k--] = t % BASE | 0; - carry = t / BASE | 0; - } - - r[k] = (r[k] + carry) % BASE | 0; - } - - // Remove trailing zeros. - for (; !r[--rL];) r.pop(); - - if (carry) ++e; - else r.shift(); - - y.d = r; - y.e = getBase10Exponent(r, e); - - return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; - }; - - - /* - * Return a string representing the value of this Decimal in base 2, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toBinary = function (sd, rm) { - return toStringBinary(this, 2, sd, rm); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` - * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. - * - * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toDecimalPlaces = P.toDP = function (dp, rm) { - var x = this, - Ctor = x.constructor; - - x = new Ctor(x); - if (dp === void 0) return x; - - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - return finalise(x, dp + x.e + 1, rm); - }; - - - /* - * Return a string representing the value of this Decimal in exponential notation rounded to - * `dp` fixed decimal places using rounding mode `rounding`. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toExponential = function (dp, rm) { - var str, - x = this, - Ctor = x.constructor; - - if (dp === void 0) { - str = finiteToString(x, true); - } else { - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - x = finalise(new Ctor(x), dp + 1, rm); - str = finiteToString(x, true, dp + 1); - } - - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return a string representing the value of this Decimal in normal (fixed-point) notation to - * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is - * omitted. - * - * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. - * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. - * (-0).toFixed(3) is '0.000'. - * (-0.5).toFixed(0) is '-0'. - * - */ - P.toFixed = function (dp, rm) { - var str, y, - x = this, - Ctor = x.constructor; - - if (dp === void 0) { - str = finiteToString(x); - } else { - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - y = finalise(new Ctor(x), dp + x.e + 1, rm); - str = finiteToString(y, false, dp + y.e + 1); - } - - // To determine whether to add the minus sign look at the value before it was rounded, - // i.e. look at `x` rather than `y`. - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return an array representing the value of this Decimal as a simple fraction with an integer - * numerator and an integer denominator. - * - * The denominator will be a positive non-zero value less than or equal to the specified maximum - * denominator. If a maximum denominator is not specified, the denominator will be the lowest - * value necessary to represent the number exactly. - * - * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity. - * - */ - P.toFraction = function (maxD) { - var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, - x = this, - xd = x.d, - Ctor = x.constructor; - - if (!xd) return new Ctor(x); - - n1 = d0 = new Ctor(1); - d1 = n0 = new Ctor(0); - - d = new Ctor(d1); - e = d.e = getPrecision(xd) - x.e - 1; - k = e % LOG_BASE; - d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k); - - if (maxD == null) { - - // d is 10**e, the minimum max-denominator needed. - maxD = e > 0 ? d : n1; - } else { - n = new Ctor(maxD); - if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n); - maxD = n.gt(d) ? (e > 0 ? d : n1) : n; - } - - external = false; - n = new Ctor(digitsToString(xd)); - pr = Ctor.precision; - Ctor.precision = e = xd.length * LOG_BASE * 2; - - for (;;) { - q = divide(n, d, 0, 1, 1); - d2 = d0.plus(q.times(d1)); - if (d2.cmp(maxD) == 1) break; - d0 = d1; - d1 = d2; - d2 = n1; - n1 = n0.plus(q.times(d2)); - n0 = d2; - d2 = d; - d = n.minus(q.times(d2)); - n = d2; - } - - d2 = divide(maxD.minus(d0), d1, 0, 1, 1); - n0 = n0.plus(d2.times(n1)); - d0 = d0.plus(d2.times(d1)); - n0.s = n1.s = x.s; - - // Determine which fraction is closer to x, n0/d0 or n1/d1? - r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 - ? [n1, d1] : [n0, d0]; - - Ctor.precision = pr; - external = true; - - return r; - }; - - - /* - * Return a string representing the value of this Decimal in base 16, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toHexadecimal = P.toHex = function (sd, rm) { - return toStringBinary(this, 16, sd, rm); - }; - - - /* - * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding - * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal. - * - * The return value will always have the same sign as this Decimal, unless either this Decimal - * or `y` is NaN, in which case the return value will be also be NaN. - * - * The return value is not affected by the value of `precision`. - * - * y {number|string|Decimal} The magnitude to round to a multiple of. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * 'toNearest() rounding mode not an integer: {rm}' - * 'toNearest() rounding mode out of range: {rm}' - * - */ - P.toNearest = function (y, rm) { - var x = this, - Ctor = x.constructor; - - x = new Ctor(x); - - if (y == null) { - - // If x is not finite, return x. - if (!x.d) return x; - - y = new Ctor(1); - rm = Ctor.rounding; - } else { - y = new Ctor(y); - if (rm === void 0) { - rm = Ctor.rounding; - } else { - checkInt32(rm, 0, 8); - } - - // If x is not finite, return x if y is not NaN, else NaN. - if (!x.d) return y.s ? x : y; - - // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN. - if (!y.d) { - if (y.s) y.s = x.s; - return y; - } - } - - // If y is not zero, calculate the nearest multiple of y to x. - if (y.d[0]) { - external = false; - x = divide(x, y, 0, rm, 1).times(y); - external = true; - finalise(x); - - // If y is zero, return zero with the sign of x. - } else { - y.s = x.s; - x = y; - } - - return x; - }; - - - /* - * Return the value of this Decimal converted to a number primitive. - * Zero keeps its sign. - * - */ - P.toNumber = function () { - return +this; - }; - - - /* - * Return a string representing the value of this Decimal in base 8, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toOctal = function (sd, rm) { - return toStringBinary(this, 8, sd, rm); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded - * to `precision` significant digits using rounding mode `rounding`. - * - * ECMAScript compliant. - * - * pow(x, NaN) = NaN - * pow(x, ±0) = 1 - - * pow(NaN, non-zero) = NaN - * pow(abs(x) > 1, +Infinity) = +Infinity - * pow(abs(x) > 1, -Infinity) = +0 - * pow(abs(x) == 1, ±Infinity) = NaN - * pow(abs(x) < 1, +Infinity) = +0 - * pow(abs(x) < 1, -Infinity) = +Infinity - * pow(+Infinity, y > 0) = +Infinity - * pow(+Infinity, y < 0) = +0 - * pow(-Infinity, odd integer > 0) = -Infinity - * pow(-Infinity, even integer > 0) = +Infinity - * pow(-Infinity, odd integer < 0) = -0 - * pow(-Infinity, even integer < 0) = +0 - * pow(+0, y > 0) = +0 - * pow(+0, y < 0) = +Infinity - * pow(-0, odd integer > 0) = -0 - * pow(-0, even integer > 0) = +0 - * pow(-0, odd integer < 0) = -Infinity - * pow(-0, even integer < 0) = +Infinity - * pow(finite x < 0, finite non-integer) = NaN - * - * For non-integer or very large exponents pow(x, y) is calculated using - * - * x^y = exp(y*ln(x)) - * - * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the - * probability of an incorrectly rounded result - * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14 - * i.e. 1 in 250,000,000,000,000 - * - * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place). - * - * y {number|string|Decimal} The power to which to raise this Decimal. - * - */ - P.toPower = P.pow = function (y) { - var e, k, pr, r, rm, s, - x = this, - Ctor = x.constructor, - yn = +(y = new Ctor(y)); - - // Either ±Infinity, NaN or ±0? - if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); - - x = new Ctor(x); - - if (x.eq(1)) return x; - - pr = Ctor.precision; - rm = Ctor.rounding; - - if (y.eq(1)) return finalise(x, pr, rm); - - // y exponent - e = mathfloor(y.e / LOG_BASE); - - // If y is a small integer use the 'exponentiation by squaring' algorithm. - if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { - r = intPow(Ctor, x, k, pr); - return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); - } - - s = x.s; - - // if x is negative - if (s < 0) { - - // if y is not an integer - if (e < y.d.length - 1) return new Ctor(NaN); - - // Result is positive if x is negative and the last digit of integer y is even. - if ((y.d[e] & 1) == 0) s = 1; - - // if x.eq(-1) - if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) { - x.s = s; - return x; - } - } - - // Estimate result exponent. - // x^y = 10^e, where e = y * log10(x) - // log10(x) = log10(x_significand) + x_exponent - // log10(x_significand) = ln(x_significand) / ln(10) - k = mathpow(+x, yn); - e = k == 0 || !isFinite(k) - ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) - : new Ctor(k + '').e; - - // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. - - // Overflow/underflow? - if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0); - - external = false; - Ctor.rounding = x.s = 1; - - // Estimate the extra guard digits needed to ensure five correct rounding digits from - // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): - // new Decimal(2.32456).pow('2087987436534566.46411') - // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 - k = Math.min(12, (e + '').length); - - // r = x^y = exp(y*ln(x)) - r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); - - // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40) - if (r.d) { - - // Truncate to the required precision plus five rounding digits. - r = finalise(r, pr + 5, 1); - - // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate - // the result. - if (checkRoundingDigits(r.d, pr, rm)) { - e = pr + 10; - - // Truncate to the increased precision plus five rounding digits. - r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); - - // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). - if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { - r = finalise(r, pr + 1, 0); - } - } - } - - r.s = s; - external = true; - Ctor.rounding = rm; - - return finalise(r, pr, rm); - }; - - - /* - * Return a string representing the value of this Decimal rounded to `sd` significant digits - * using rounding mode `rounding`. - * - * Return exponential notation if `sd` is less than the number of digits necessary to represent - * the integer part of the value in normal notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toPrecision = function (sd, rm) { - var str, - x = this, - Ctor = x.constructor; - - if (sd === void 0) { - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - } else { - checkInt32(sd, 1, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - x = finalise(new Ctor(x), sd, rm); - str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd); - } - - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` - * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if - * omitted. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * 'toSD() digits out of range: {sd}' - * 'toSD() digits not an integer: {sd}' - * 'toSD() rounding mode not an integer: {rm}' - * 'toSD() rounding mode out of range: {rm}' - * - */ - P.toSignificantDigits = P.toSD = function (sd, rm) { - var x = this, - Ctor = x.constructor; - - if (sd === void 0) { - sd = Ctor.precision; - rm = Ctor.rounding; - } else { - checkInt32(sd, 1, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - } - - return finalise(new Ctor(x), sd, rm); - }; - - - /* - * Return a string representing the value of this Decimal. - * - * Return exponential notation if this Decimal has a positive exponent equal to or greater than - * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. - * - */ - P.toString = function () { - var x = this, - Ctor = x.constructor, - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal truncated to a whole number. - * - */ - P.truncated = P.trunc = function () { - return finalise(new this.constructor(this), this.e + 1, 1); - }; - - - /* - * Return a string representing the value of this Decimal. - * Unlike `toString`, negative zero will include the minus sign. - * - */ - P.valueOf = P.toJSON = function () { - var x = this, - Ctor = x.constructor, - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - - return x.isNeg() ? '-' + str : str; - }; - - - /* - // Add aliases to match BigDecimal method names. - // P.add = P.plus; - P.subtract = P.minus; - P.multiply = P.times; - P.divide = P.div; - P.remainder = P.mod; - P.compareTo = P.cmp; - P.negate = P.neg; - */ - - - // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. - - - /* - * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower, - * finiteToString, naturalExponential, naturalLogarithm - * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest, - * P.toPrecision, P.toSignificantDigits, toStringBinary, random - * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm - * convertBase toStringBinary, parseOther - * cos P.cos - * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy, - * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction, - * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm, - * taylorSeries, atan2, parseOther - * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh, - * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus, - * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot, - * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed, - * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits, - * P.truncated, divide, getLn10, getPi, naturalExponential, - * naturalLogarithm, ceil, floor, round, trunc - * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf, - * toStringBinary - * getBase10Exponent P.minus, P.plus, P.times, parseOther - * getLn10 P.logarithm, naturalLogarithm - * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2 - * getPrecision P.precision, P.toFraction - * getZeroString digitsToString, finiteToString - * intPow P.toPower, parseOther - * isOdd toLessThanHalfPi - * maxOrMin max, min - * naturalExponential P.naturalExponential, P.toPower - * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm, - * P.toPower, naturalExponential - * nonFiniteToString finiteToString, toStringBinary - * parseDecimal Decimal - * parseOther Decimal - * sin P.sin - * taylorSeries P.cosh, P.sinh, cos, sin - * toLessThanHalfPi P.cos, P.sin - * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal - * truncate intPow - * - * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi, - * naturalLogarithm, config, parseOther, random, Decimal - */ - - - function digitsToString(d) { - var i, k, ws, - indexOfLastWord = d.length - 1, - str = '', - w = d[0]; - - if (indexOfLastWord > 0) { - str += w; - for (i = 1; i < indexOfLastWord; i++) { - ws = d[i] + ''; - k = LOG_BASE - ws.length; - if (k) str += getZeroString(k); - str += ws; - } - - w = d[i]; - ws = w + ''; - k = LOG_BASE - ws.length; - if (k) str += getZeroString(k); - } else if (w === 0) { - return '0'; - } - - // Remove trailing zeros of last w. - for (; w % 10 === 0;) w /= 10; - - return str + w; - } - - - function checkInt32(i, min, max) { - if (i !== ~~i || i < min || i > max) { - throw Error(invalidArgument + i); - } - } - - - /* - * Check 5 rounding digits if `repeating` is null, 4 otherwise. - * `repeating == null` if caller is `log` or `pow`, - * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`. - */ - function checkRoundingDigits(d, i, rm, repeating) { - var di, k, r, rd; - - // Get the length of the first word of the array d. - for (k = d[0]; k >= 10; k /= 10) --i; - - // Is the rounding digit in the first word of d? - if (--i < 0) { - i += LOG_BASE; - di = 0; - } else { - di = Math.ceil((i + 1) / LOG_BASE); - i %= LOG_BASE; - } - - // i is the index (0 - 6) of the rounding digit. - // E.g. if within the word 3487563 the first rounding digit is 5, - // then i = 4, k = 1000, rd = 3487563 % 1000 = 563 - k = mathpow(10, LOG_BASE - i); - rd = d[di] % k | 0; - - if (repeating == null) { - if (i < 3) { - if (i == 0) rd = rd / 100 | 0; - else if (i == 1) rd = rd / 10 | 0; - r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0; - } else { - r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && - (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || - (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0; - } - } else { - if (i < 4) { - if (i == 0) rd = rd / 1000 | 0; - else if (i == 1) rd = rd / 100 | 0; - else if (i == 2) rd = rd / 10 | 0; - r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999; - } else { - r = ((repeating || rm < 4) && rd + 1 == k || - (!repeating && rm > 3) && rd + 1 == k / 2) && - (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1; - } - } - - return r; - } - - - // Convert string of `baseIn` to an array of numbers of `baseOut`. - // Eg. convertBase('255', 10, 16) returns [15, 15]. - // Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. - function convertBase(str, baseIn, baseOut) { - var j, - arr = [0], - arrL, - i = 0, - strL = str.length; - - for (; i < strL;) { - for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn; - arr[0] += NUMERALS.indexOf(str.charAt(i++)); - for (j = 0; j < arr.length; j++) { - if (arr[j] > baseOut - 1) { - if (arr[j + 1] === void 0) arr[j + 1] = 0; - arr[j + 1] += arr[j] / baseOut | 0; - arr[j] %= baseOut; - } - } - } - - return arr.reverse(); - } - - - /* - * cos(x) = 1 - x^2/2! + x^4/4! - ... - * |x| < pi/2 - * - */ - function cosine(Ctor, x) { - var k, y, - len = x.d.length; - - // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1 - // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1 - - // Estimate the optimum number of times to use the argument reduction. - if (len < 32) { - k = Math.ceil(len / 3); - y = (1 / tinyPow(4, k)).toString(); - } else { - k = 16; - y = '2.3283064365386962890625e-10'; - } - - Ctor.precision += k; - - x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1)); - - // Reverse argument reduction - for (var i = k; i--;) { - var cos2x = x.times(x); - x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1); - } - - Ctor.precision -= k; - - return x; - } - - - /* - * Perform division in the specified base. - */ - var divide = (function () { - - // Assumes non-zero x and k, and hence non-zero result. - function multiplyInteger(x, k, base) { - var temp, - carry = 0, - i = x.length; - - for (x = x.slice(); i--;) { - temp = x[i] * k + carry; - x[i] = temp % base | 0; - carry = temp / base | 0; - } - - if (carry) x.unshift(carry); - - return x; - } - - function compare(a, b, aL, bL) { - var i, r; - - if (aL != bL) { - r = aL > bL ? 1 : -1; - } else { - for (i = r = 0; i < aL; i++) { - if (a[i] != b[i]) { - r = a[i] > b[i] ? 1 : -1; - break; - } - } - } - - return r; - } - - function subtract(a, b, aL, base) { - var i = 0; - - // Subtract b from a. - for (; aL--;) { - a[aL] -= i; - i = a[aL] < b[aL] ? 1 : 0; - a[aL] = i * base + a[aL] - b[aL]; - } - - // Remove leading zeros. - for (; !a[0] && a.length > 1;) a.shift(); - } - - return function (x, y, pr, rm, dp, base) { - var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, - yL, yz, - Ctor = x.constructor, - sign = x.s == y.s ? 1 : -1, - xd = x.d, - yd = y.d; - - // Either NaN, Infinity or 0? - if (!xd || !xd[0] || !yd || !yd[0]) { - - return new Ctor(// Return NaN if either NaN, or both Infinity or 0. - !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN : - - // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0. - xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0); - } - - if (base) { - logBase = 1; - e = x.e - y.e; - } else { - base = BASE; - logBase = LOG_BASE; - e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase); - } - - yL = yd.length; - xL = xd.length; - q = new Ctor(sign); - qd = q.d = []; - - // Result exponent may be one less than e. - // The digit array of a Decimal from toStringBinary may have trailing zeros. - for (i = 0; yd[i] == (xd[i] || 0); i++); - - if (yd[i] > (xd[i] || 0)) e--; - - if (pr == null) { - sd = pr = Ctor.precision; - rm = Ctor.rounding; - } else if (dp) { - sd = pr + (x.e - y.e) + 1; - } else { - sd = pr; - } - - if (sd < 0) { - qd.push(1); - more = true; - } else { - - // Convert precision in number of base 10 digits to base 1e7 digits. - sd = sd / logBase + 2 | 0; - i = 0; - - // divisor < 1e7 - if (yL == 1) { - k = 0; - yd = yd[0]; - sd++; - - // k is the carry. - for (; (i < xL || k) && sd--; i++) { - t = k * base + (xd[i] || 0); - qd[i] = t / yd | 0; - k = t % yd | 0; - } - - more = k || i < xL; - - // divisor >= 1e7 - } else { - - // Normalise xd and yd so highest order digit of yd is >= base/2 - k = base / (yd[0] + 1) | 0; - - if (k > 1) { - yd = multiplyInteger(yd, k, base); - xd = multiplyInteger(xd, k, base); - yL = yd.length; - xL = xd.length; - } - - xi = yL; - rem = xd.slice(0, yL); - remL = rem.length; - - // Add zeros to make remainder as long as divisor. - for (; remL < yL;) rem[remL++] = 0; - - yz = yd.slice(); - yz.unshift(0); - yd0 = yd[0]; - - if (yd[1] >= base / 2) ++yd0; - - do { - k = 0; - - // Compare divisor and remainder. - cmp = compare(yd, rem, yL, remL); - - // If divisor < remainder. - if (cmp < 0) { - - // Calculate trial digit, k. - rem0 = rem[0]; - if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); - - // k will be how many times the divisor goes into the current remainder. - k = rem0 / yd0 | 0; - - // Algorithm: - // 1. product = divisor * trial digit (k) - // 2. if product > remainder: product -= divisor, k-- - // 3. remainder -= product - // 4. if product was < remainder at 2: - // 5. compare new remainder and divisor - // 6. If remainder > divisor: remainder -= divisor, k++ - - if (k > 1) { - if (k >= base) k = base - 1; - - // product = divisor * trial digit. - prod = multiplyInteger(yd, k, base); - prodL = prod.length; - remL = rem.length; - - // Compare product and remainder. - cmp = compare(prod, rem, prodL, remL); - - // product > remainder. - if (cmp == 1) { - k--; - - // Subtract divisor from product. - subtract(prod, yL < prodL ? yz : yd, prodL, base); - } - } else { - - // cmp is -1. - // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1 - // to avoid it. If k is 1 there is a need to compare yd and rem again below. - if (k == 0) cmp = k = 1; - prod = yd.slice(); - } - - prodL = prod.length; - if (prodL < remL) prod.unshift(0); - - // Subtract product from remainder. - subtract(rem, prod, remL, base); - - // If product was < previous remainder. - if (cmp == -1) { - remL = rem.length; - - // Compare divisor and new remainder. - cmp = compare(yd, rem, yL, remL); - - // If divisor < new remainder, subtract divisor from remainder. - if (cmp < 1) { - k++; - - // Subtract divisor from remainder. - subtract(rem, yL < remL ? yz : yd, remL, base); - } - } - - remL = rem.length; - } else if (cmp === 0) { - k++; - rem = [0]; - } // if cmp === 1, k will be 0 - - // Add the next digit, k, to the result array. - qd[i++] = k; - - // Update the remainder. - if (cmp && rem[0]) { - rem[remL++] = xd[xi] || 0; - } else { - rem = [xd[xi]]; - remL = 1; - } - - } while ((xi++ < xL || rem[0] !== void 0) && sd--); - - more = rem[0] !== void 0; - } - - // Leading zero? - if (!qd[0]) qd.shift(); - } - - // logBase is 1 when divide is being used for base conversion. - if (logBase == 1) { - q.e = e; - inexact = more; - } else { - - // To calculate q.e, first get the number of digits of qd[0]. - for (i = 1, k = qd[0]; k >= 10; k /= 10) i++; - q.e = i + e * logBase - 1; - - finalise(q, dp ? pr + q.e + 1 : pr, rm, more); - } - - return q; - }; - })(); - - - /* - * Round `x` to `sd` significant digits using rounding mode `rm`. - * Check for over/under-flow. - */ - function finalise(x, sd, rm, isTruncated) { - var digits, i, j, k, rd, roundUp, w, xd, xdi, - Ctor = x.constructor; - - // Don't round if sd is null or undefined. - out: if (sd != null) { - xd = x.d; - - // Infinity/NaN. - if (!xd) return x; - - // rd: the rounding digit, i.e. the digit after the digit that may be rounded up. - // w: the word of xd containing rd, a base 1e7 number. - // xdi: the index of w within xd. - // digits: the number of digits of w. - // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if - // they had leading zeros) - // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero). - - // Get the length of the first word of the digits array xd. - for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++; - i = sd - digits; - - // Is the rounding digit in the first word of xd? - if (i < 0) { - i += LOG_BASE; - j = sd; - w = xd[xdi = 0]; - - // Get the rounding digit at index j of w. - rd = w / mathpow(10, digits - j - 1) % 10 | 0; - } else { - xdi = Math.ceil((i + 1) / LOG_BASE); - k = xd.length; - if (xdi >= k) { - if (isTruncated) { - - // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`. - for (; k++ <= xdi;) xd.push(0); - w = rd = 0; - digits = 1; - i %= LOG_BASE; - j = i - LOG_BASE + 1; - } else { - break out; - } - } else { - w = k = xd[xdi]; - - // Get the number of digits of w. - for (digits = 1; k >= 10; k /= 10) digits++; - - // Get the index of rd within w. - i %= LOG_BASE; - - // Get the index of rd within w, adjusted for leading zeros. - // The number of leading zeros of w is given by LOG_BASE - digits. - j = i - LOG_BASE + digits; - - // Get the rounding digit at index j of w. - rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0; - } - } - - // Are there any non-zero digits after the rounding digit? - isTruncated = isTruncated || sd < 0 || - xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1)); - - // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right - // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression - // will give 714. - - roundUp = rm < 4 - ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) - : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 && - - // Check whether the digit to the left of the rounding digit is odd. - ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 || - rm == (x.s < 0 ? 8 : 7)); - - if (sd < 1 || !xd[0]) { - xd.length = 0; - if (roundUp) { - - // Convert sd to decimal places. - sd -= x.e + 1; - - // 1, 0.1, 0.01, 0.001, 0.0001 etc. - xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE); - x.e = -sd || 0; - } else { - - // Zero. - xd[0] = x.e = 0; - } - - return x; - } - - // Remove excess digits. - if (i == 0) { - xd.length = xdi; - k = 1; - xdi--; - } else { - xd.length = xdi + 1; - k = mathpow(10, LOG_BASE - i); - - // E.g. 56700 becomes 56000 if 7 is the rounding digit. - // j > 0 means i > number of leading zeros of w. - xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0; - } - - if (roundUp) { - for (;;) { - - // Is the digit to be rounded up in the first word of xd? - if (xdi == 0) { - - // i will be the length of xd[0] before k is added. - for (i = 1, j = xd[0]; j >= 10; j /= 10) i++; - j = xd[0] += k; - for (k = 1; j >= 10; j /= 10) k++; - - // if i != k the length has increased. - if (i != k) { - x.e++; - if (xd[0] == BASE) xd[0] = 1; - } - - break; - } else { - xd[xdi] += k; - if (xd[xdi] != BASE) break; - xd[xdi--] = 0; - k = 1; - } - } - } - - // Remove trailing zeros. - for (i = xd.length; xd[--i] === 0;) xd.pop(); - } - - if (external) { - - // Overflow? - if (x.e > Ctor.maxE) { - - // Infinity. - x.d = null; - x.e = NaN; - - // Underflow? - } else if (x.e < Ctor.minE) { - - // Zero. - x.e = 0; - x.d = [0]; - // Ctor.underflow = true; - } // else Ctor.underflow = false; - } - - return x; - } - - - function finiteToString(x, isExp, sd) { - if (!x.isFinite()) return nonFiniteToString(x); - var k, - e = x.e, - str = digitsToString(x.d), - len = str.length; - - if (isExp) { - if (sd && (k = sd - len) > 0) { - str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k); - } else if (len > 1) { - str = str.charAt(0) + '.' + str.slice(1); - } - - str = str + (x.e < 0 ? 'e' : 'e+') + x.e; - } else if (e < 0) { - str = '0.' + getZeroString(-e - 1) + str; - if (sd && (k = sd - len) > 0) str += getZeroString(k); - } else if (e >= len) { - str += getZeroString(e + 1 - len); - if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k); - } else { - if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k); - if (sd && (k = sd - len) > 0) { - if (e + 1 === len) str += '.'; - str += getZeroString(k); - } - } - - return str; - } - - - // Calculate the base 10 exponent from the base 1e7 exponent. - function getBase10Exponent(digits, e) { - var w = digits[0]; - - // Add the number of digits of the first word of the digits array. - for ( e *= LOG_BASE; w >= 10; w /= 10) e++; - return e; - } - - - function getLn10(Ctor, sd, pr) { - if (sd > LN10_PRECISION) { - - // Reset global state in case the exception is caught. - external = true; - if (pr) Ctor.precision = pr; - throw Error(precisionLimitExceeded); - } - return finalise(new Ctor(LN10), sd, 1, true); - } - - - function getPi(Ctor, sd, rm) { - if (sd > PI_PRECISION) throw Error(precisionLimitExceeded); - return finalise(new Ctor(PI), sd, rm, true); - } - - - function getPrecision(digits) { - var w = digits.length - 1, - len = w * LOG_BASE + 1; - - w = digits[w]; - - // If non-zero... - if (w) { - - // Subtract the number of trailing zeros of the last word. - for (; w % 10 == 0; w /= 10) len--; - - // Add the number of digits of the first word. - for (w = digits[0]; w >= 10; w /= 10) len++; - } - - return len; - } - - - function getZeroString(k) { - var zs = ''; - for (; k--;) zs += '0'; - return zs; - } - - - /* - * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an - * integer of type number. - * - * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`. - * - */ - function intPow(Ctor, x, n, pr) { - var isTruncated, - r = new Ctor(1), - - // Max n of 9007199254740991 takes 53 loop iterations. - // Maximum digits array length; leaves [28, 34] guard digits. - k = Math.ceil(pr / LOG_BASE + 4); - - external = false; - - for (;;) { - if (n % 2) { - r = r.times(x); - if (truncate(r.d, k)) isTruncated = true; - } - - n = mathfloor(n / 2); - if (n === 0) { - - // To ensure correct rounding when r.d is truncated, increment the last word if it is zero. - n = r.d.length - 1; - if (isTruncated && r.d[n] === 0) ++r.d[n]; - break; - } - - x = x.times(x); - truncate(x.d, k); - } - - external = true; - - return r; - } - - - function isOdd(n) { - return n.d[n.d.length - 1] & 1; - } - - - /* - * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'. - */ - function maxOrMin(Ctor, args, ltgt) { - var y, - x = new Ctor(args[0]), - i = 0; - - for (; ++i < args.length;) { - y = new Ctor(args[i]); - if (!y.s) { - x = y; - break; - } else if (x[ltgt](y)) { - x = y; - } - } - - return x; - } - - - /* - * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant - * digits. - * - * Taylor/Maclaurin series. - * - * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ... - * - * Argument reduction: - * Repeat x = x / 32, k += 5, until |x| < 0.1 - * exp(x) = exp(x / 2^k)^(2^k) - * - * Previously, the argument was initially reduced by - * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10) - * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was - * found to be slower than just dividing repeatedly by 32 as above. - * - * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000 - * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000 - * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324) - * - * exp(Infinity) = Infinity - * exp(-Infinity) = 0 - * exp(NaN) = NaN - * exp(±0) = 1 - * - * exp(x) is non-terminating for any finite, non-zero x. - * - * The result will always be correctly rounded. - * - */ - function naturalExponential(x, sd) { - var denominator, guard, j, pow, sum, t, wpr, - rep = 0, - i = 0, - k = 0, - Ctor = x.constructor, - rm = Ctor.rounding, - pr = Ctor.precision; - - // 0/NaN/Infinity? - if (!x.d || !x.d[0] || x.e > 17) { - - return new Ctor(x.d - ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 - : x.s ? x.s < 0 ? 0 : x : 0 / 0); - } - - if (sd == null) { - external = false; - wpr = pr; - } else { - wpr = sd; - } - - t = new Ctor(0.03125); - - // while abs(x) >= 0.1 - while (x.e > -2) { - - // x = x / 2^5 - x = x.times(t); - k += 5; - } - - // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision - // necessary to ensure the first 4 rounding digits are correct. - guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0; - wpr += guard; - denominator = pow = sum = new Ctor(1); - Ctor.precision = wpr; - - for (;;) { - pow = finalise(pow.times(x), wpr, 1); - denominator = denominator.times(++i); - t = sum.plus(divide(pow, denominator, wpr, 1)); - - if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { - j = k; - while (j--) sum = finalise(sum.times(sum), wpr, 1); - - // Check to see if the first 4 rounding digits are [49]999. - // If so, repeat the summation with a higher precision, otherwise - // e.g. with precision: 18, rounding: 1 - // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123) - // `wpr - guard` is the index of first rounding digit. - if (sd == null) { - - if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { - Ctor.precision = wpr += 10; - denominator = pow = t = new Ctor(1); - i = 0; - rep++; - } else { - return finalise(sum, Ctor.precision = pr, rm, external = true); - } - } else { - Ctor.precision = pr; - return sum; - } - } - - sum = t; - } - } - - - /* - * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant - * digits. - * - * ln(-n) = NaN - * ln(0) = -Infinity - * ln(-0) = -Infinity - * ln(1) = 0 - * ln(Infinity) = Infinity - * ln(-Infinity) = NaN - * ln(NaN) = NaN - * - * ln(n) (n != 1) is non-terminating. - * - */ - function naturalLogarithm(y, sd) { - var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2, - n = 1, - guard = 10, - x = y, - xd = x.d, - Ctor = x.constructor, - rm = Ctor.rounding, - pr = Ctor.precision; - - // Is x negative or Infinity, NaN, 0 or 1? - if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) { - return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x); - } - - if (sd == null) { - external = false; - wpr = pr; - } else { - wpr = sd; - } - - Ctor.precision = wpr += guard; - c = digitsToString(xd); - c0 = c.charAt(0); - - if (Math.abs(e = x.e) < 1.5e15) { - - // Argument reduction. - // The series converges faster the closer the argument is to 1, so using - // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b - // multiply the argument by itself until the leading digits of the significand are 7, 8, 9, - // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can - // later be divided by this number, then separate out the power of 10 using - // ln(a*10^b) = ln(a) + b*ln(10). - - // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14). - //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) { - // max n is 6 (gives 0.7 - 1.3) - while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) { - x = x.times(y); - c = digitsToString(x.d); - c0 = c.charAt(0); - n++; - } - - e = x.e; - - if (c0 > 1) { - x = new Ctor('0.' + c); - e++; - } else { - x = new Ctor(c0 + '.' + c.slice(1)); - } - } else { - - // The argument reduction method above may result in overflow if the argument y is a massive - // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this - // function using ln(x*10^e) = ln(x) + e*ln(10). - t = getLn10(Ctor, wpr + 2, pr).times(e + ''); - x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t); - Ctor.precision = pr; - - return sd == null ? finalise(x, pr, rm, external = true) : x; - } - - // x1 is x reduced to a value near 1. - x1 = x; - - // Taylor series. - // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...) - // where x = (y - 1)/(y + 1) (|x| < 1) - sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1); - x2 = finalise(x.times(x), wpr, 1); - denominator = 3; - - for (;;) { - numerator = finalise(numerator.times(x2), wpr, 1); - t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1)); - - if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { - sum = sum.times(2); - - // Reverse the argument reduction. Check that e is not 0 because, besides preventing an - // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0. - if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + '')); - sum = divide(sum, new Ctor(n), wpr, 1); - - // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has - // been repeated previously) and the first 4 rounding digits 9999? - // If so, restart the summation with a higher precision, otherwise - // e.g. with precision: 12, rounding: 1 - // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463. - // `wpr - guard` is the index of first rounding digit. - if (sd == null) { - if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { - Ctor.precision = wpr += guard; - t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1); - x2 = finalise(x.times(x), wpr, 1); - denominator = rep = 1; - } else { - return finalise(sum, Ctor.precision = pr, rm, external = true); - } - } else { - Ctor.precision = pr; - return sum; - } - } - - sum = t; - denominator += 2; - } - } - - - // ±Infinity, NaN. - function nonFiniteToString(x) { - // Unsigned. - return String(x.s * x.s / 0); - } - - - /* - * Parse the value of a new Decimal `x` from string `str`. - */ - function parseDecimal(x, str) { - var e, i, len; - - // Decimal point? - if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); - - // Exponential form? - if ((i = str.search(/e/i)) > 0) { - - // Determine exponent. - if (e < 0) e = i; - e += +str.slice(i + 1); - str = str.substring(0, i); - } else if (e < 0) { - - // Integer. - e = str.length; - } - - // Determine leading zeros. - for (i = 0; str.charCodeAt(i) === 48; i++); - - // Determine trailing zeros. - for (len = str.length; str.charCodeAt(len - 1) === 48; --len); - str = str.slice(i, len); - - if (str) { - len -= i; - x.e = e = e - i - 1; - x.d = []; - - // Transform base - - // e is the base 10 exponent. - // i is where to slice str to get the first word of the digits array. - i = (e + 1) % LOG_BASE; - if (e < 0) i += LOG_BASE; - - if (i < len) { - if (i) x.d.push(+str.slice(0, i)); - for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE)); - str = str.slice(i); - i = LOG_BASE - str.length; - } else { - i -= len; - } - - for (; i--;) str += '0'; - x.d.push(+str); - - if (external) { - - // Overflow? - if (x.e > x.constructor.maxE) { - - // Infinity. - x.d = null; - x.e = NaN; - - // Underflow? - } else if (x.e < x.constructor.minE) { - - // Zero. - x.e = 0; - x.d = [0]; - // x.constructor.underflow = true; - } // else x.constructor.underflow = false; - } - } else { - - // Zero. - x.e = 0; - x.d = [0]; - } - - return x; - } - - - /* - * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value. - */ - function parseOther(x, str) { - var base, Ctor, divisor, i, isFloat, len, p, xd, xe; - - if (str === 'Infinity' || str === 'NaN') { - if (!+str) x.s = NaN; - x.e = NaN; - x.d = null; - return x; - } - - if (isHex.test(str)) { - base = 16; - str = str.toLowerCase(); - } else if (isBinary.test(str)) { - base = 2; - } else if (isOctal.test(str)) { - base = 8; - } else { - throw Error(invalidArgument + str); - } - - // Is there a binary exponent part? - i = str.search(/p/i); - - if (i > 0) { - p = +str.slice(i + 1); - str = str.substring(2, i); - } else { - str = str.slice(2); - } - - // Convert `str` as an integer then divide the result by `base` raised to a power such that the - // fraction part will be restored. - i = str.indexOf('.'); - isFloat = i >= 0; - Ctor = x.constructor; - - if (isFloat) { - str = str.replace('.', ''); - len = str.length; - i = len - i; - - // log[10](16) = 1.2041... , log[10](88) = 1.9444.... - divisor = intPow(Ctor, new Ctor(base), i, i * 2); - } - - xd = convertBase(str, base, BASE); - xe = xd.length - 1; - - // Remove trailing zeros. - for (i = xe; xd[i] === 0; --i) xd.pop(); - if (i < 0) return new Ctor(x.s * 0); - x.e = getBase10Exponent(xd, xe); - x.d = xd; - external = false; - - // At what precision to perform the division to ensure exact conversion? - // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount) - // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412 - // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits. - // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount - // Therefore using 4 * the number of digits of str will always be enough. - if (isFloat) x = divide(x, divisor, len * 4); - - // Multiply by the binary exponent part if present. - if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p)); - external = true; - - return x; - } - - - /* - * sin(x) = x - x^3/3! + x^5/5! - ... - * |x| < pi/2 - * - */ - function sine(Ctor, x) { - var k, - len = x.d.length; - - if (len < 3) return taylorSeries(Ctor, 2, x, x); - - // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x) - // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5) - // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20)) - - // Estimate the optimum number of times to use the argument reduction. - k = 1.4 * Math.sqrt(len); - k = k > 16 ? 16 : k | 0; - - x = x.times(1 / tinyPow(5, k)); - x = taylorSeries(Ctor, 2, x, x); - - // Reverse argument reduction - var sin2_x, - d5 = new Ctor(5), - d16 = new Ctor(16), - d20 = new Ctor(20); - for (; k--;) { - sin2_x = x.times(x); - x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20)))); - } - - return x; - } - - - // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`. - function taylorSeries(Ctor, n, x, y, isHyperbolic) { - var j, t, u, x2, - i = 1, - pr = Ctor.precision, - k = Math.ceil(pr / LOG_BASE); - - external = false; - x2 = x.times(x); - u = new Ctor(y); - - for (;;) { - t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1); - u = isHyperbolic ? y.plus(t) : y.minus(t); - y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1); - t = u.plus(y); - - if (t.d[k] !== void 0) { - for (j = k; t.d[j] === u.d[j] && j--;); - if (j == -1) break; - } - - j = u; - u = y; - y = t; - t = j; - i++; - } - - external = true; - t.d.length = k + 1; - - return t; - } - - - // Exponent e must be positive and non-zero. - function tinyPow(b, e) { - var n = b; - while (--e) n *= b; - return n; - } - - - // Return the absolute value of `x` reduced to less than or equal to half pi. - function toLessThanHalfPi(Ctor, x) { - var t, - isNeg = x.s < 0, - pi = getPi(Ctor, Ctor.precision, 1), - halfPi = pi.times(0.5); - - x = x.abs(); - - if (x.lte(halfPi)) { - quadrant = isNeg ? 4 : 1; - return x; - } - - t = x.divToInt(pi); - - if (t.isZero()) { - quadrant = isNeg ? 3 : 2; - } else { - x = x.minus(t.times(pi)); - - // 0 <= x < pi - if (x.lte(halfPi)) { - quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1); - return x; - } - - quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2); - } - - return x.minus(pi).abs(); - } - - - /* - * Return the value of Decimal `x` as a string in base `baseOut`. - * - * If the optional `sd` argument is present include a binary exponent suffix. - */ - function toStringBinary(x, baseOut, sd, rm) { - var base, e, i, k, len, roundUp, str, xd, y, - Ctor = x.constructor, - isExp = sd !== void 0; - - if (isExp) { - checkInt32(sd, 1, MAX_DIGITS); - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - } else { - sd = Ctor.precision; - rm = Ctor.rounding; - } - - if (!x.isFinite()) { - str = nonFiniteToString(x); - } else { - str = finiteToString(x); - i = str.indexOf('.'); - - // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required: - // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10)) - // minBinaryExponent = floor(decimalExponent * log[2](10)) - // log[2](10) = 3.321928094887362347870319429489390175864 - - if (isExp) { - base = 2; - if (baseOut == 16) { - sd = sd * 4 - 3; - } else if (baseOut == 8) { - sd = sd * 3 - 2; - } - } else { - base = baseOut; - } - - // Convert the number as an integer then divide the result by its base raised to a power such - // that the fraction part will be restored. - - // Non-integer. - if (i >= 0) { - str = str.replace('.', ''); - y = new Ctor(1); - y.e = str.length - i; - y.d = convertBase(finiteToString(y), 10, base); - y.e = y.d.length; - } - - xd = convertBase(str, 10, base); - e = len = xd.length; - - // Remove trailing zeros. - for (; xd[--len] == 0;) xd.pop(); - - if (!xd[0]) { - str = isExp ? '0p+0' : '0'; - } else { - if (i < 0) { - e--; - } else { - x = new Ctor(x); - x.d = xd; - x.e = e; - x = divide(x, y, sd, rm, 0, base); - xd = x.d; - e = x.e; - roundUp = inexact; - } - - // The rounding digit, i.e. the digit after the digit that may be rounded up. - i = xd[sd]; - k = base / 2; - roundUp = roundUp || xd[sd + 1] !== void 0; - - roundUp = rm < 4 - ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2)) - : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || - rm === (x.s < 0 ? 8 : 7)); - - xd.length = sd; - - if (roundUp) { - - // Rounding up may mean the previous digit has to be rounded up and so on. - for (; ++xd[--sd] > base - 1;) { - xd[sd] = 0; - if (!sd) { - ++e; - xd.unshift(1); - } - } - } - - // Determine trailing zeros. - for (len = xd.length; !xd[len - 1]; --len); - - // E.g. [4, 11, 15] becomes 4bf. - for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]); - - // Add binary exponent suffix? - if (isExp) { - if (len > 1) { - if (baseOut == 16 || baseOut == 8) { - i = baseOut == 16 ? 4 : 3; - for (--len; len % i; len++) str += '0'; - xd = convertBase(str, base, baseOut); - for (len = xd.length; !xd[len - 1]; --len); - - // xd[0] will always be be 1 - for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]); - } else { - str = str.charAt(0) + '.' + str.slice(1); - } - } - - str = str + (e < 0 ? 'p' : 'p+') + e; - } else if (e < 0) { - for (; ++e;) str = '0' + str; - str = '0.' + str; - } else { - if (++e > len) for (e -= len; e-- ;) str += '0'; - else if (e < len) str = str.slice(0, e) + '.' + str.slice(e); - } - } - - str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str; - } - - return x.s < 0 ? '-' + str : str; - } - - - // Does not strip trailing zeros. - function truncate(arr, len) { - if (arr.length > len) { - arr.length = len; - return true; - } - } - - - // Decimal methods - - - /* - * abs - * acos - * acosh - * add - * asin - * asinh - * atan - * atanh - * atan2 - * cbrt - * ceil - * clone - * config - * cos - * cosh - * div - * exp - * floor - * hypot - * ln - * log - * log2 - * log10 - * max - * min - * mod - * mul - * pow - * random - * round - * set - * sign - * sin - * sinh - * sqrt - * sub - * tan - * tanh - * trunc - */ - - - /* - * Return a new Decimal whose value is the absolute value of `x`. - * - * x {number|string|Decimal} - * - */ - function abs(x) { - return new this(x).abs(); - } - - - /* - * Return a new Decimal whose value is the arccosine in radians of `x`. - * - * x {number|string|Decimal} - * - */ - function acos(x) { - return new this(x).acos(); - } - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function acosh(x) { - return new this(x).acosh(); - } - - - /* - * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function add(x, y) { - return new this(x).plus(y); - } - - - /* - * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function asin(x) { - return new this(x).asin(); - } - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function asinh(x) { - return new this(x).asinh(); - } - - - /* - * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function atan(x) { - return new this(x).atan(); - } - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function atanh(x) { - return new this(x).atanh(); - } - - - /* - * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi - * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi, pi] - * - * y {number|string|Decimal} The y-coordinate. - * x {number|string|Decimal} The x-coordinate. - * - * atan2(±0, -0) = ±pi - * atan2(±0, +0) = ±0 - * atan2(±0, -x) = ±pi for x > 0 - * atan2(±0, x) = ±0 for x > 0 - * atan2(-y, ±0) = -pi/2 for y > 0 - * atan2(y, ±0) = pi/2 for y > 0 - * atan2(±y, -Infinity) = ±pi for finite y > 0 - * atan2(±y, +Infinity) = ±0 for finite y > 0 - * atan2(±Infinity, x) = ±pi/2 for finite x - * atan2(±Infinity, -Infinity) = ±3*pi/4 - * atan2(±Infinity, +Infinity) = ±pi/4 - * atan2(NaN, x) = NaN - * atan2(y, NaN) = NaN - * - */ - function atan2(y, x) { - y = new this(y); - x = new this(x); - var r, - pr = this.precision, - rm = this.rounding, - wpr = pr + 4; - - // Either NaN - if (!y.s || !x.s) { - r = new this(NaN); - - // Both ±Infinity - } else if (!y.d && !x.d) { - r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75); - r.s = y.s; - - // x is ±Infinity or y is ±0 - } else if (!x.d || y.isZero()) { - r = x.s < 0 ? getPi(this, pr, rm) : new this(0); - r.s = y.s; - - // y is ±Infinity or x is ±0 - } else if (!y.d || x.isZero()) { - r = getPi(this, wpr, 1).times(0.5); - r.s = y.s; - - // Both non-zero and finite - } else if (x.s < 0) { - this.precision = wpr; - this.rounding = 1; - r = this.atan(divide(y, x, wpr, 1)); - x = getPi(this, wpr, 1); - this.precision = pr; - this.rounding = rm; - r = y.s < 0 ? r.minus(x) : r.plus(x); - } else { - r = this.atan(divide(y, x, wpr, 1)); - } - - return r; - } - - - /* - * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function cbrt(x) { - return new this(x).cbrt(); - } - - - /* - * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`. - * - * x {number|string|Decimal} - * - */ - function ceil(x) { - return finalise(x = new this(x), x.e + 1, 2); - } - - - /* - * Configure global settings for a Decimal constructor. - * - * `obj` is an object with one or more of the following properties, - * - * precision {number} - * rounding {number} - * toExpNeg {number} - * toExpPos {number} - * maxE {number} - * minE {number} - * modulo {number} - * crypto {boolean|number} - * defaults {true} - * - * E.g. Decimal.config({ precision: 20, rounding: 4 }) - * - */ - function config(obj) { - if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); - var i, p, v, - useDefaults = obj.defaults === true, - ps = [ - 'precision', 1, MAX_DIGITS, - 'rounding', 0, 8, - 'toExpNeg', -EXP_LIMIT, 0, - 'toExpPos', 0, EXP_LIMIT, - 'maxE', 0, EXP_LIMIT, - 'minE', -EXP_LIMIT, 0, - 'modulo', 0, 9 - ]; - - for (i = 0; i < ps.length; i += 3) { - if (p = ps[i], useDefaults) this[p] = DEFAULTS[p]; - if ((v = obj[p]) !== void 0) { - if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; - else throw Error(invalidArgument + p + ': ' + v); - } - } - - if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p]; - if ((v = obj[p]) !== void 0) { - if (v === true || v === false || v === 0 || v === 1) { - if (v) { - if (typeof crypto != 'undefined' && crypto && - (crypto.getRandomValues || crypto.randomBytes)) { - this[p] = true; - } else { - throw Error(cryptoUnavailable); - } - } else { - this[p] = false; - } - } else { - throw Error(invalidArgument + p + ': ' + v); - } - } - - return this; - } - - - /* - * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function cos(x) { - return new this(x).cos(); - } - - - /* - * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function cosh(x) { - return new this(x).cosh(); - } - - - /* - * Create and return a Decimal constructor with the same configuration properties as this Decimal - * constructor. - * - */ - function clone(obj) { - var i, p, ps; - - /* - * The Decimal constructor and exported function. - * Return a new Decimal instance. - * - * v {number|string|Decimal} A numeric value. - * - */ - function Decimal(v) { - var e, i, t, - x = this; - - // Decimal called without new. - if (!(x instanceof Decimal)) return new Decimal(v); - - // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor - // which points to Object. - x.constructor = Decimal; - - // Duplicate. - if (v instanceof Decimal) { - x.s = v.s; - - if (external) { - if (!v.d || v.e > Decimal.maxE) { - - // Infinity. - x.e = NaN; - x.d = null; - } else if (v.e < Decimal.minE) { - - // Zero. - x.e = 0; - x.d = [0]; - } else { - x.e = v.e; - x.d = v.d.slice(); - } - } else { - x.e = v.e; - x.d = v.d ? v.d.slice() : v.d; - } - - return; - } - - t = typeof v; - - if (t === 'number') { - if (v === 0) { - x.s = 1 / v < 0 ? -1 : 1; - x.e = 0; - x.d = [0]; - return; - } - - if (v < 0) { - v = -v; - x.s = -1; - } else { - x.s = 1; - } - - // Fast path for small integers. - if (v === ~~v && v < 1e7) { - for (e = 0, i = v; i >= 10; i /= 10) e++; - - if (external) { - if (e > Decimal.maxE) { - x.e = NaN; - x.d = null; - } else if (e < Decimal.minE) { - x.e = 0; - x.d = [0]; - } else { - x.e = e; - x.d = [v]; - } - } else { - x.e = e; - x.d = [v]; - } - - return; - - // Infinity, NaN. - } else if (v * 0 !== 0) { - if (!v) x.s = NaN; - x.e = NaN; - x.d = null; - return; - } - - return parseDecimal(x, v.toString()); - - } else if (t !== 'string') { - throw Error(invalidArgument + v); - } - - // Minus sign? - if ((i = v.charCodeAt(0)) === 45) { - v = v.slice(1); - x.s = -1; - } else { - // Plus sign? - if (i === 43) v = v.slice(1); - x.s = 1; - } - - return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); - } - - Decimal.prototype = P; - - Decimal.ROUND_UP = 0; - Decimal.ROUND_DOWN = 1; - Decimal.ROUND_CEIL = 2; - Decimal.ROUND_FLOOR = 3; - Decimal.ROUND_HALF_UP = 4; - Decimal.ROUND_HALF_DOWN = 5; - Decimal.ROUND_HALF_EVEN = 6; - Decimal.ROUND_HALF_CEIL = 7; - Decimal.ROUND_HALF_FLOOR = 8; - Decimal.EUCLID = 9; - - Decimal.config = Decimal.set = config; - Decimal.clone = clone; - Decimal.isDecimal = isDecimalInstance; - - Decimal.abs = abs; - Decimal.acos = acos; - Decimal.acosh = acosh; // ES6 - Decimal.add = add; - Decimal.asin = asin; - Decimal.asinh = asinh; // ES6 - Decimal.atan = atan; - Decimal.atanh = atanh; // ES6 - Decimal.atan2 = atan2; - Decimal.cbrt = cbrt; // ES6 - Decimal.ceil = ceil; - Decimal.cos = cos; - Decimal.cosh = cosh; // ES6 - Decimal.div = div; - Decimal.exp = exp; - Decimal.floor = floor; - Decimal.hypot = hypot; // ES6 - Decimal.ln = ln; - Decimal.log = log; - Decimal.log10 = log10; // ES6 - Decimal.log2 = log2; // ES6 - Decimal.max = max; - Decimal.min = min; - Decimal.mod = mod; - Decimal.mul = mul; - Decimal.pow = pow; - Decimal.random = random; - Decimal.round = round; - Decimal.sign = sign; // ES6 - Decimal.sin = sin; - Decimal.sinh = sinh; // ES6 - Decimal.sqrt = sqrt; - Decimal.sub = sub; - Decimal.tan = tan; - Decimal.tanh = tanh; // ES6 - Decimal.trunc = trunc; // ES6 - - if (obj === void 0) obj = {}; - if (obj) { - if (obj.defaults !== true) { - ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto']; - for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; - } - } - - Decimal.config(obj); - - return Decimal; - } - - - /* - * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function div(x, y) { - return new this(x).div(y); - } - - - /* - * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} The power to which to raise the base of the natural log. - * - */ - function exp(x) { - return new this(x).exp(); - } - - - /* - * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`. - * - * x {number|string|Decimal} - * - */ - function floor(x) { - return finalise(x = new this(x), x.e + 1, 3); - } - - - /* - * Return a new Decimal whose value is the square root of the sum of the squares of the arguments, - * rounded to `precision` significant digits using rounding mode `rounding`. - * - * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...) - * - * arguments {number|string|Decimal} - * - */ - function hypot() { - var i, n, - t = new this(0); - - external = false; - - for (i = 0; i < arguments.length;) { - n = new this(arguments[i++]); - if (!n.d) { - if (n.s) { - external = true; - return new this(1 / 0); - } - t = n; - } else if (t.d) { - t = t.plus(n.times(n)); - } - } - - external = true; - - return t.sqrt(); - } - - - /* - * Return true if object is a Decimal instance (where Decimal is any Decimal constructor), - * otherwise return false. - * - */ - function isDecimalInstance(obj) { - return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false; - } - - - /* - * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function ln(x) { - return new this(x).ln(); - } - - - /* - * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base - * is specified, rounded to `precision` significant digits using rounding mode `rounding`. - * - * log[y](x) - * - * x {number|string|Decimal} The argument of the logarithm. - * y {number|string|Decimal} The base of the logarithm. - * - */ - function log(x, y) { - return new this(x).log(y); - } - - - /* - * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function log2(x) { - return new this(x).log(2); - } - - - /* - * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function log10(x) { - return new this(x).log(10); - } - - - /* - * Return a new Decimal whose value is the maximum of the arguments. - * - * arguments {number|string|Decimal} - * - */ - function max() { - return maxOrMin(this, arguments, 'lt'); - } - - - /* - * Return a new Decimal whose value is the minimum of the arguments. - * - * arguments {number|string|Decimal} - * - */ - function min() { - return maxOrMin(this, arguments, 'gt'); - } - - - /* - * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function mod(x, y) { - return new this(x).mod(y); - } - - - /* - * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function mul(x, y) { - return new this(x).mul(y); - } - - - /* - * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} The base. - * y {number|string|Decimal} The exponent. - * - */ - function pow(x, y) { - return new this(x).pow(y); - } - - - /* - * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with - * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros - * are produced). - * - * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive. - * - */ - function random(sd) { - var d, e, k, n, - i = 0, - r = new this(1), - rd = []; - - if (sd === void 0) sd = this.precision; - else checkInt32(sd, 1, MAX_DIGITS); - - k = Math.ceil(sd / LOG_BASE); - - if (!this.crypto) { - for (; i < k;) rd[i++] = Math.random() * 1e7 | 0; - - // Browsers supporting crypto.getRandomValues. - } else if (crypto.getRandomValues) { - d = crypto.getRandomValues(new Uint32Array(k)); - - for (; i < k;) { - n = d[i]; - - // 0 <= n < 4294967296 - // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865). - if (n >= 4.29e9) { - d[i] = crypto.getRandomValues(new Uint32Array(1))[0]; - } else { - - // 0 <= n <= 4289999999 - // 0 <= (n % 1e7) <= 9999999 - rd[i++] = n % 1e7; - } - } - - // Node.js supporting crypto.randomBytes. - } else if (crypto.randomBytes) { - - // buffer - d = crypto.randomBytes(k *= 4); - - for (; i < k;) { - - // 0 <= n < 2147483648 - n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24); - - // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286). - if (n >= 2.14e9) { - crypto.randomBytes(4).copy(d, i); - } else { - - // 0 <= n <= 2139999999 - // 0 <= (n % 1e7) <= 9999999 - rd.push(n % 1e7); - i += 4; - } - } - - i = k / 4; - } else { - throw Error(cryptoUnavailable); - } - - k = rd[--i]; - sd %= LOG_BASE; - - // Convert trailing digits to zeros according to sd. - if (k && sd) { - n = mathpow(10, LOG_BASE - sd); - rd[i] = (k / n | 0) * n; - } - - // Remove trailing words which are zero. - for (; rd[i] === 0; i--) rd.pop(); - - // Zero? - if (i < 0) { - e = 0; - rd = [0]; - } else { - e = -1; - - // Remove leading words which are zero and adjust exponent accordingly. - for (; rd[0] === 0; e -= LOG_BASE) rd.shift(); - - // Count the digits of the first word of rd to determine leading zeros. - for (k = 1, n = rd[0]; n >= 10; n /= 10) k++; - - // Adjust the exponent for leading zeros of the first word of rd. - if (k < LOG_BASE) e -= LOG_BASE - k; - } - - r.e = e; - r.d = rd; - - return r; - } - - - /* - * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`. - * - * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL). - * - * x {number|string|Decimal} - * - */ - function round(x) { - return finalise(x = new this(x), x.e + 1, this.rounding); - } - - - /* - * Return - * 1 if x > 0, - * -1 if x < 0, - * 0 if x is 0, - * -0 if x is -0, - * NaN otherwise - * - * x {number|string|Decimal} - * - */ - function sign(x) { - x = new this(x); - return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN; - } - - - /* - * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function sin(x) { - return new this(x).sin(); - } - - - /* - * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function sinh(x) { - return new this(x).sinh(); - } - - - /* - * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function sqrt(x) { - return new this(x).sqrt(); - } - - - /* - * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function sub(x, y) { - return new this(x).sub(y); - } - - - /* - * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function tan(x) { - return new this(x).tan(); - } - - - /* - * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function tanh(x) { - return new this(x).tanh(); - } - - - /* - * Return a new Decimal whose value is `x` truncated to an integer. - * - * x {number|string|Decimal} - * - */ - function trunc(x) { - return finalise(x = new this(x), x.e + 1, 1); - } - - - // Create and configure initial Decimal constructor. - Decimal = clone(DEFAULTS); - - Decimal['default'] = Decimal.Decimal = Decimal; - - // Create the internal constants from their string values. - LN10 = new Decimal(LN10); - PI = new Decimal(PI); - - - // Export. - - - // AMD. - if (typeof define == 'function' && define.amd) { - define(function () { - return Decimal; - }); - - // Node and other environments that support module.exports. - } else if ( true && module.exports) { - if (typeof Symbol == 'function' && typeof Symbol.iterator == 'symbol') { - P[Symbol.for('nodejs.util.inspect.custom')] = P.toString; - P[Symbol.toStringTag] = 'Decimal'; - } - - module.exports = Decimal; - - // Browser. - } else { - if (!globalScope) { - globalScope = typeof self != 'undefined' && self && self.self == self ? self : window; - } - - noConflict = globalScope.Decimal; - Decimal.noConflict = function () { - globalScope.Decimal = noConflict; - return Decimal; - }; - - globalScope.Decimal = Decimal; - } -})(this); - +;(function (globalScope) { + 'use strict'; -/***/ }), -/***/ 18611: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /* + * decimal.js v10.2.1 + * An arbitrary-precision Decimal type for JavaScript. + * https://github.com/MikeMcl/decimal.js + * Copyright (c) 2020 Michael Mclaughlin + * MIT Licence + */ -var Stream = __nccwpck_require__(92413).Stream; -var util = __nccwpck_require__(31669); -module.exports = DelayedStream; -function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; + // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ // - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; -} -util.inherits(DelayedStream, Stream); -DelayedStream.create = function(source, options) { - var delayedStream = new this(); + // The maximum exponent magnitude. + // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`. + var EXP_LIMIT = 9e15, // 0 to 9e15 - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; - } + // The limit on the value of `precision`, and on the value of the first argument to + // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`. + MAX_DIGITS = 1e9, // 0 to 1e9 - delayedStream.source = source; + // Base conversion alphabet. + NUMERALS = '0123456789abcdef', - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; + // The natural logarithm of 10 (1025 digits). + LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058', - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); - } + // Pi (1025 digits). + PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789', - return delayedStream; -}; -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; - } -}); + // The initial configuration properties of the Decimal constructor. + DEFAULTS = { -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); -}; + // These values must be integers within the stated ranges (inclusive). + // Most of these values can be changed at run-time using the `Decimal.config` method. -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); - } + // The maximum number of significant digits of the result of a calculation or base conversion. + // E.g. `Decimal.config({ precision: 20 });` + precision: 20, // 1 to MAX_DIGITS - this.source.resume(); -}; + // The rounding mode used when rounding to `precision`. + // + // ROUND_UP 0 Away from zero. + // ROUND_DOWN 1 Towards zero. + // ROUND_CEIL 2 Towards +Infinity. + // ROUND_FLOOR 3 Towards -Infinity. + // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + // + // E.g. + // `Decimal.rounding = 4;` + // `Decimal.rounding = Decimal.ROUND_HALF_UP;` + rounding: 4, // 0 to 8 + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend (JavaScript %). + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 The IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive. + // + // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian + // division (9) are commonly used for the modulus operation. The other rounding modes can also + // be used, but they may not give useful results. + modulo: 1, // 0 to 9 -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; + // The exponent value at and beneath which `toString` returns exponential notation. + // JavaScript numbers: -7 + toExpNeg: -7, // 0 to -EXP_LIMIT -DelayedStream.prototype.release = function() { - this._released = true; + // The exponent value at and above which `toString` returns exponential notation. + // JavaScript numbers: 21 + toExpPos: 21, // 0 to EXP_LIMIT - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; + // The minimum exponent value, beneath which underflow to zero occurs. + // JavaScript numbers: -324 (5e-324) + minE: -EXP_LIMIT, // -1 to -EXP_LIMIT -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; + // The maximum exponent value, above which overflow to Infinity occurs. + // JavaScript numbers: 308 (1.7976931348623157e+308) + maxE: EXP_LIMIT, // 1 to EXP_LIMIT -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; - } + // Whether to use cryptographically-secure random number generation, if available. + crypto: false // true/false + }, - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } - this._bufferedEvents.push(args); -}; + // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- // -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } - if (this.dataSize <= this.maxDataSize) { - return; - } + Decimal, inexact, noConflict, quadrant, + external = true, - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; + decimalError = '[DecimalError] ', + invalidArgument = decimalError + 'Invalid argument: ', + precisionLimitExceeded = decimalError + 'Precision limit exceeded', + cryptoUnavailable = decimalError + 'crypto unavailable', + mathfloor = Math.floor, + mathpow = Math.pow, -/***/ }), + isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i, + isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i, + isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i, + isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, -/***/ 85589: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + BASE = 1e7, + LOG_BASE = 7, + MAX_SAFE_INTEGER = 9007199254740991, -"use strict"; + LN10_PRECISION = LN10.length - 1, + PI_PRECISION = PI.length - 1, -const legacyErrorCodes = __nccwpck_require__(37297); -const idlUtils = __nccwpck_require__(69497); + // Decimal.prototype object + P = { name: '[object Decimal]' }; -exports.implementation = class DOMExceptionImpl { - constructor(globalObject, [message, name]) { - this.name = name; - this.message = message; - } - get code() { - return legacyErrorCodes[this.name] || 0; - } -}; + // Decimal prototype methods -// A proprietary V8 extension that causes the stack property to appear. -exports.init = impl => { - if (Error.captureStackTrace) { - const wrapper = idlUtils.wrapperForImpl(impl); - Error.captureStackTrace(wrapper, wrapper.constructor); - } -}; + /* + * absoluteValue abs + * ceil + * comparedTo cmp + * cosine cos + * cubeRoot cbrt + * decimalPlaces dp + * dividedBy div + * dividedToIntegerBy divToInt + * equals eq + * floor + * greaterThan gt + * greaterThanOrEqualTo gte + * hyperbolicCosine cosh + * hyperbolicSine sinh + * hyperbolicTangent tanh + * inverseCosine acos + * inverseHyperbolicCosine acosh + * inverseHyperbolicSine asinh + * inverseHyperbolicTangent atanh + * inverseSine asin + * inverseTangent atan + * isFinite + * isInteger isInt + * isNaN + * isNegative isNeg + * isPositive isPos + * isZero + * lessThan lt + * lessThanOrEqualTo lte + * logarithm log + * [maximum] [max] + * [minimum] [min] + * minus sub + * modulo mod + * naturalExponential exp + * naturalLogarithm ln + * negated neg + * plus add + * precision sd + * round + * sine sin + * squareRoot sqrt + * tangent tan + * times mul + * toBinary + * toDecimalPlaces toDP + * toExponential + * toFixed + * toFraction + * toHexadecimal toHex + * toNearest + * toNumber + * toOctal + * toPower pow + * toPrecision + * toSignificantDigits toSD + * toString + * truncated trunc + * valueOf toJSON + */ -/***/ }), -/***/ 37561: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /* + * Return a new Decimal whose value is the absolute value of this Decimal. + * + */ + P.absoluteValue = P.abs = function () { + var x = new this.constructor(this); + if (x.s < 0) x.s = 1; + return finalise(x); + }; -"use strict"; + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of positive Infinity. + * + */ + P.ceil = function () { + return finalise(new this.constructor(this), this.e + 1, 2); + }; -const conversions = __nccwpck_require__(19463); -const utils = __nccwpck_require__(69497); -const impl = utils.implSymbol; -const ctorRegistry = utils.ctorRegistrySymbol; + /* + * Return + * 1 if the value of this Decimal is greater than the value of `y`, + * -1 if the value of this Decimal is less than the value of `y`, + * 0 if they have the same value, + * NaN if the value of either Decimal is NaN. + * + */ + P.comparedTo = P.cmp = function (y) { + var i, j, xdL, ydL, + x = this, + xd = x.d, + yd = (y = new x.constructor(y)).d, + xs = x.s, + ys = y.s; -const iface = { - // When an interface-module that implements this interface as a mixin is loaded, it will append its own `.is()` - // method into this array. It allows objects that directly implements *those* interfaces to be recognized as - // implementing this mixin interface. - _mixedIntoPredicates: [], - is(obj) { - if (obj) { - if (utils.hasOwn(obj, impl) && obj[impl] instanceof Impl.implementation) { - return true; - } - for (const isMixedInto of module.exports._mixedIntoPredicates) { - if (isMixedInto(obj)) { - return true; - } - } + // Either NaN or ±Infinity? + if (!xd || !yd) { + return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; } - return false; - }, - isImpl(obj) { - if (obj) { - if (obj instanceof Impl.implementation) { - return true; - } - const wrapper = utils.wrapperForImpl(obj); - for (const isMixedInto of module.exports._mixedIntoPredicates) { - if (isMixedInto(wrapper)) { - return true; - } - } - } - return false; - }, - convert(obj, { context = "The provided value" } = {}) { - if (module.exports.is(obj)) { - return utils.implForWrapper(obj); - } - throw new TypeError(`${context} is not of type 'DOMException'.`); - }, + // Either zero? + if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; - create(globalObject, constructorArgs, privateData) { - if (globalObject[ctorRegistry] === undefined) { - throw new Error("Internal error: invalid global object"); - } + // Signs differ? + if (xs !== ys) return xs; - const ctor = globalObject[ctorRegistry]["DOMException"]; - if (ctor === undefined) { - throw new Error("Internal error: constructor DOMException is not installed on the passed global object"); + // Compare exponents. + if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; + + xdL = xd.length; + ydL = yd.length; + + // Compare digit by digit. + for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { + if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; } - let obj = Object.create(ctor.prototype); - obj = iface.setup(obj, globalObject, constructorArgs, privateData); - return obj; - }, - createImpl(globalObject, constructorArgs, privateData) { - const obj = iface.create(globalObject, constructorArgs, privateData); - return utils.implForWrapper(obj); - }, - _internalSetup(obj) {}, - setup(obj, globalObject, constructorArgs = [], privateData = {}) { - privateData.wrapper = obj; + // Compare lengths. + return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; + }; - iface._internalSetup(obj); - Object.defineProperty(obj, impl, { - value: new Impl.implementation(globalObject, constructorArgs, privateData), - configurable: true - }); - obj[impl][utils.wrapperSymbol] = obj; - if (Impl.init) { - Impl.init(obj[impl], privateData); + /* + * Return a new Decimal whose value is the cosine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * cos(0) = 1 + * cos(-0) = 1 + * cos(Infinity) = NaN + * cos(-Infinity) = NaN + * cos(NaN) = NaN + * + */ + P.cosine = P.cos = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.d) return new Ctor(NaN); + + // cos(0) = cos(-0) = 1 + if (!x.d[0]) return new Ctor(1); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; + + x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); + }; + + + /* + * + * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * cbrt(0) = 0 + * cbrt(-0) = -0 + * cbrt(1) = 1 + * cbrt(-1) = -1 + * cbrt(N) = N + * cbrt(-I) = -I + * cbrt(I) = I + * + * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3)) + * + */ + P.cubeRoot = P.cbrt = function () { + var e, m, n, r, rep, s, sd, t, t3, t3plusx, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + external = false; + + // Initial estimate. + s = x.s * mathpow(x.s * x, 1 / 3); + + // Math.cbrt underflow/overflow? + // Pass x to Math.pow as integer, then adjust the exponent of the result. + if (!s || Math.abs(s) == 1 / 0) { + n = digitsToString(x.d); + e = x.e; + + // Adjust n exponent so it is a multiple of 3 away from x exponent. + if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); + s = mathpow(n, 1 / 3); + + // Rarely, e may be one less than the result exponent value. + e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + r.s = x.s; + } else { + r = new Ctor(s.toString()); } - return obj; - }, - install(globalObject) { - class DOMException { - constructor() { - const args = []; - { - let curArg = arguments[0]; - if (curArg !== undefined) { - curArg = conversions["DOMString"](curArg, { context: "Failed to construct 'DOMException': parameter 1" }); - } else { - curArg = ""; + sd = (e = Ctor.precision) + 3; + + // Halley's method. + // TODO? Compare Newton's method. + for (;;) { + t = r; + t3 = t.times(t).times(t); + t3plusx = t3.plus(x); + r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); + + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 + // , i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); + + if (t.times(t).times(t).eq(x)) { + r = t; + break; + } } - args.push(curArg); - } - { - let curArg = arguments[1]; - if (curArg !== undefined) { - curArg = conversions["DOMString"](curArg, { context: "Failed to construct 'DOMException': parameter 2" }); - } else { - curArg = "Error"; + + sd += 4; + rep = 1; + } else { + + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).times(r).eq(x); } - args.push(curArg); + + break; } - return iface.setup(Object.create(new.target.prototype), globalObject, args); } + } - get name() { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } + external = true; - return this[impl]["name"]; - } + return finalise(r, e, Ctor.rounding, m); + }; - get message() { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } - return this[impl]["message"]; - } + /* + * Return the number of decimal places of the value of this Decimal. + * + */ + P.decimalPlaces = P.dp = function () { + var w, + d = this.d, + n = NaN; - get code() { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } + if (d) { + w = d.length - 1; + n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; - return this[impl]["code"]; - } - } - Object.defineProperties(DOMException.prototype, { - name: { enumerable: true }, - message: { enumerable: true }, - code: { enumerable: true }, - [Symbol.toStringTag]: { value: "DOMException", configurable: true }, - INDEX_SIZE_ERR: { value: 1, enumerable: true }, - DOMSTRING_SIZE_ERR: { value: 2, enumerable: true }, - HIERARCHY_REQUEST_ERR: { value: 3, enumerable: true }, - WRONG_DOCUMENT_ERR: { value: 4, enumerable: true }, - INVALID_CHARACTER_ERR: { value: 5, enumerable: true }, - NO_DATA_ALLOWED_ERR: { value: 6, enumerable: true }, - NO_MODIFICATION_ALLOWED_ERR: { value: 7, enumerable: true }, - NOT_FOUND_ERR: { value: 8, enumerable: true }, - NOT_SUPPORTED_ERR: { value: 9, enumerable: true }, - INUSE_ATTRIBUTE_ERR: { value: 10, enumerable: true }, - INVALID_STATE_ERR: { value: 11, enumerable: true }, - SYNTAX_ERR: { value: 12, enumerable: true }, - INVALID_MODIFICATION_ERR: { value: 13, enumerable: true }, - NAMESPACE_ERR: { value: 14, enumerable: true }, - INVALID_ACCESS_ERR: { value: 15, enumerable: true }, - VALIDATION_ERR: { value: 16, enumerable: true }, - TYPE_MISMATCH_ERR: { value: 17, enumerable: true }, - SECURITY_ERR: { value: 18, enumerable: true }, - NETWORK_ERR: { value: 19, enumerable: true }, - ABORT_ERR: { value: 20, enumerable: true }, - URL_MISMATCH_ERR: { value: 21, enumerable: true }, - QUOTA_EXCEEDED_ERR: { value: 22, enumerable: true }, - TIMEOUT_ERR: { value: 23, enumerable: true }, - INVALID_NODE_TYPE_ERR: { value: 24, enumerable: true }, - DATA_CLONE_ERR: { value: 25, enumerable: true } - }); - Object.defineProperties(DOMException, { - INDEX_SIZE_ERR: { value: 1, enumerable: true }, - DOMSTRING_SIZE_ERR: { value: 2, enumerable: true }, - HIERARCHY_REQUEST_ERR: { value: 3, enumerable: true }, - WRONG_DOCUMENT_ERR: { value: 4, enumerable: true }, - INVALID_CHARACTER_ERR: { value: 5, enumerable: true }, - NO_DATA_ALLOWED_ERR: { value: 6, enumerable: true }, - NO_MODIFICATION_ALLOWED_ERR: { value: 7, enumerable: true }, - NOT_FOUND_ERR: { value: 8, enumerable: true }, - NOT_SUPPORTED_ERR: { value: 9, enumerable: true }, - INUSE_ATTRIBUTE_ERR: { value: 10, enumerable: true }, - INVALID_STATE_ERR: { value: 11, enumerable: true }, - SYNTAX_ERR: { value: 12, enumerable: true }, - INVALID_MODIFICATION_ERR: { value: 13, enumerable: true }, - NAMESPACE_ERR: { value: 14, enumerable: true }, - INVALID_ACCESS_ERR: { value: 15, enumerable: true }, - VALIDATION_ERR: { value: 16, enumerable: true }, - TYPE_MISMATCH_ERR: { value: 17, enumerable: true }, - SECURITY_ERR: { value: 18, enumerable: true }, - NETWORK_ERR: { value: 19, enumerable: true }, - ABORT_ERR: { value: 20, enumerable: true }, - URL_MISMATCH_ERR: { value: 21, enumerable: true }, - QUOTA_EXCEEDED_ERR: { value: 22, enumerable: true }, - TIMEOUT_ERR: { value: 23, enumerable: true }, - INVALID_NODE_TYPE_ERR: { value: 24, enumerable: true }, - DATA_CLONE_ERR: { value: 25, enumerable: true } - }); - if (globalObject[ctorRegistry] === undefined) { - globalObject[ctorRegistry] = Object.create(null); + // Subtract the number of trailing zeros of the last word. + w = d[w]; + if (w) for (; w % 10 == 0; w /= 10) n--; + if (n < 0) n = 0; } - globalObject[ctorRegistry]["DOMException"] = DOMException; - - Object.defineProperty(globalObject, "DOMException", { - configurable: true, - writable: true, - value: DOMException - }); - } -}; // iface -module.exports = iface; -const Impl = __nccwpck_require__(85589); + return n; + }; -/***/ }), + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + */ + P.dividedBy = P.div = function (y) { + return divide(this, new this.constructor(y)); + }; -/***/ 69497: -/***/ ((module, exports) => { -"use strict"; + /* + * Return a new Decimal whose value is the integer part of dividing the value of this Decimal + * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`. + * + */ + P.dividedToIntegerBy = P.divToInt = function (y) { + var x = this, + Ctor = x.constructor; + return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); + }; -// Returns "Type(value) is Object" in ES terminology. -function isObject(value) { - return typeof value === "object" && value !== null || typeof value === "function"; -} + /* + * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. + * + */ + P.equals = P.eq = function (y) { + return this.cmp(y) === 0; + }; -function hasOwn(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} -const wrapperSymbol = Symbol("wrapper"); -const implSymbol = Symbol("impl"); -const sameObjectCaches = Symbol("SameObject caches"); -const ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry"); + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of negative Infinity. + * + */ + P.floor = function () { + return finalise(new this.constructor(this), this.e + 1, 3); + }; -function getSameObject(wrapper, prop, creator) { - if (!wrapper[sameObjectCaches]) { - wrapper[sameObjectCaches] = Object.create(null); - } - if (prop in wrapper[sameObjectCaches]) { - return wrapper[sameObjectCaches][prop]; - } + /* + * Return true if the value of this Decimal is greater than the value of `y`, otherwise return + * false. + * + */ + P.greaterThan = P.gt = function (y) { + return this.cmp(y) > 0; + }; - wrapper[sameObjectCaches][prop] = creator(); - return wrapper[sameObjectCaches][prop]; -} -function wrapperForImpl(impl) { - return impl ? impl[wrapperSymbol] : null; -} + /* + * Return true if the value of this Decimal is greater than or equal to the value of `y`, + * otherwise return false. + * + */ + P.greaterThanOrEqualTo = P.gte = function (y) { + var k = this.cmp(y); + return k == 1 || k === 0; + }; -function implForWrapper(wrapper) { - return wrapper ? wrapper[implSymbol] : null; -} -function tryWrapperForImpl(impl) { - const wrapper = wrapperForImpl(impl); - return wrapper ? wrapper : impl; -} + /* + * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [1, Infinity] + * + * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ... + * + * cosh(0) = 1 + * cosh(-0) = 1 + * cosh(Infinity) = Infinity + * cosh(-Infinity) = Infinity + * cosh(NaN) = NaN + * + * x time taken (ms) result + * 1000 9 9.8503555700852349694e+433 + * 10000 25 4.4034091128314607936e+4342 + * 100000 171 1.4033316802130615897e+43429 + * 1000000 3817 1.5166076984010437725e+434294 + * 10000000 abandoned after 2 minute wait + * + * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x)) + * + */ + P.hyperbolicCosine = P.cosh = function () { + var k, n, pr, rm, len, + x = this, + Ctor = x.constructor, + one = new Ctor(1); + + if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); + if (x.isZero()) return one; + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; + + // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 + // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) + + // Estimate the optimum number of times to use the argument reduction. + // TODO? Estimation reused from cosine() and may not be optimal here. + if (len < 32) { + k = Math.ceil(len / 3); + n = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + n = '2.3283064365386962890625e-10'; + } -function tryImplForWrapper(wrapper) { - const impl = implForWrapper(wrapper); - return impl ? impl : wrapper; -} + x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); -const iterInternalSymbol = Symbol("internal"); -const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); + // Reverse argument reduction + var cosh2_x, + i = k, + d8 = new Ctor(8); + for (; i--;) { + cosh2_x = x.times(x); + x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); + } -function isArrayIndexPropName(P) { - if (typeof P !== "string") { - return false; - } - const i = P >>> 0; - if (i === Math.pow(2, 32) - 1) { - return false; - } - const s = `${i}`; - if (P !== s) { - return false; - } - return true; -} + return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); + }; -const byteLengthGetter = - Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; -function isArrayBuffer(value) { - try { - byteLengthGetter.call(value); - return true; - } catch (e) { - return false; - } -} -const supportsPropertyIndex = Symbol("supports property index"); -const supportedPropertyIndices = Symbol("supported property indices"); -const supportsPropertyName = Symbol("supports property name"); -const supportedPropertyNames = Symbol("supported property names"); -const indexedGet = Symbol("indexed property get"); -const indexedSetNew = Symbol("indexed property set new"); -const indexedSetExisting = Symbol("indexed property set existing"); -const namedGet = Symbol("named property get"); -const namedSetNew = Symbol("named property set new"); -const namedSetExisting = Symbol("named property set existing"); -const namedDelete = Symbol("named property delete"); + /* + * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ... + * + * sinh(0) = 0 + * sinh(-0) = -0 + * sinh(Infinity) = Infinity + * sinh(-Infinity) = -Infinity + * sinh(NaN) = NaN + * + * x time taken (ms) + * 10 2 ms + * 100 5 ms + * 1000 14 ms + * 10000 82 ms + * 100000 886 ms 1.4033316802130615897e+43429 + * 200000 2613 ms + * 300000 5407 ms + * 400000 8824 ms + * 500000 13026 ms 8.7080643612718084129e+217146 + * 1000000 48543 ms + * + * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x)) + * + */ + P.hyperbolicSine = P.sinh = function () { + var k, pr, rm, len, + x = this, + Ctor = x.constructor; -module.exports = exports = { - isObject, - hasOwn, - wrapperSymbol, - implSymbol, - getSameObject, - ctorRegistrySymbol, - wrapperForImpl, - implForWrapper, - tryWrapperForImpl, - tryImplForWrapper, - iterInternalSymbol, - IteratorPrototype, - isArrayBuffer, - isArrayIndexPropName, - supportsPropertyIndex, - supportedPropertyIndices, - supportsPropertyName, - supportedPropertyNames, - indexedGet, - indexedSetNew, - indexedSetExisting, - namedGet, - namedSetNew, - namedSetExisting, - namedDelete -}; + if (!x.isFinite() || x.isZero()) return new Ctor(x); + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; -/***/ }), + if (len < 3) { + x = taylorSeries(Ctor, 2, x, x, true); + } else { -/***/ 19463: -/***/ ((__unused_webpack_module, exports) => { + // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) + // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) + // 3 multiplications and 1 addition -"use strict"; + // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) + // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) + // 4 multiplications and 2 additions + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; -function _(message, opts) { - return `${opts && opts.context ? opts.context : "Value"} ${message}.`; -} + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x, true); -function type(V) { - if (V === null) { - return "Null"; - } - switch (typeof V) { - case "undefined": - return "Undefined"; - case "boolean": - return "Boolean"; - case "number": - return "Number"; - case "string": - return "String"; - case "symbol": - return "Symbol"; - case "object": - // Falls through - case "function": - // Falls through - default: - // Per ES spec, typeof returns an implemention-defined value that is not any of the existing ones for - // uncallable non-standard exotic objects. Yet Type() which the Web IDL spec depends on returns Object for - // such cases. So treat the default case as an object. - return "Object"; + // Reverse argument reduction + var sinh2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sinh2_x = x.times(x); + x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); + } } -} -// Round x to the nearest integer, choosing the even integer if it lies halfway between two. -function evenRound(x) { - // There are four cases for numbers with fractional part being .5: - // - // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example - // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0 - // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2 - // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0 - // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2 - // (where n is a non-negative integer) - // - // Branch here for cases 1 and 4 - if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) || - (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) { - return censorNegativeZero(Math.floor(x)); - } + Ctor.precision = pr; + Ctor.rounding = rm; - return censorNegativeZero(Math.round(x)); -} + return finalise(x, pr, rm, true); + }; -function integerPart(n) { - return censorNegativeZero(Math.trunc(n)); -} -function sign(x) { - return x < 0 ? -1 : 1; -} + /* + * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * tanh(x) = sinh(x) / cosh(x) + * + * tanh(0) = 0 + * tanh(-0) = -0 + * tanh(Infinity) = 1 + * tanh(-Infinity) = -1 + * tanh(NaN) = NaN + * + */ + P.hyperbolicTangent = P.tanh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; -function modulo(x, y) { - // https://tc39.github.io/ecma262/#eqn-modulo - // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos - const signMightNotMatch = x % y; - if (sign(y) !== sign(signMightNotMatch)) { - return signMightNotMatch + y; - } - return signMightNotMatch; -} + if (!x.isFinite()) return new Ctor(x.s); + if (x.isZero()) return new Ctor(x); -function censorNegativeZero(x) { - return x === 0 ? 0 : x; -} + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 7; + Ctor.rounding = 1; -function createIntegerConversion(bitLength, typeOpts) { - const isSigned = !typeOpts.unsigned; + return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); + }; - let lowerBound; - let upperBound; - if (bitLength === 64) { - upperBound = Math.pow(2, 53) - 1; - lowerBound = !isSigned ? 0 : -Math.pow(2, 53) + 1; - } else if (!isSigned) { - lowerBound = 0; - upperBound = Math.pow(2, bitLength) - 1; - } else { - lowerBound = -Math.pow(2, bitLength - 1); - upperBound = Math.pow(2, bitLength - 1) - 1; + + /* + * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of + * this Decimal. + * + * Domain: [-1, 1] + * Range: [0, pi] + * + * acos(x) = pi/2 - asin(x) + * + * acos(0) = pi/2 + * acos(-0) = pi/2 + * acos(1) = 0 + * acos(-1) = pi + * acos(1/2) = pi/3 + * acos(-1/2) = 2*pi/3 + * acos(|x| > 1) = NaN + * acos(NaN) = NaN + * + */ + P.inverseCosine = P.acos = function () { + var halfPi, + x = this, + Ctor = x.constructor, + k = x.abs().cmp(1), + pr = Ctor.precision, + rm = Ctor.rounding; + + if (k !== -1) { + return k === 0 + // |x| is 1 + ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) + // |x| > 1 or x is NaN + : new Ctor(NaN); } - const twoToTheBitLength = Math.pow(2, bitLength); - const twoToOneLessThanTheBitLength = Math.pow(2, bitLength - 1); + if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); - return (V, opts) => { - if (opts === undefined) { - opts = {}; - } + // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 - let x = +V; - x = censorNegativeZero(x); // Spec discussion ongoing: https://github.com/heycam/webidl/issues/306 + Ctor.precision = pr + 6; + Ctor.rounding = 1; - if (opts.enforceRange) { - if (!Number.isFinite(x)) { - throw new TypeError(_("is not a finite number", opts)); - } + x = x.asin(); + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); - x = integerPart(x); + Ctor.precision = pr; + Ctor.rounding = rm; - if (x < lowerBound || x > upperBound) { - throw new TypeError(_( - `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts)); - } + return halfPi.minus(x); + }; - return x; - } - if (!Number.isNaN(x) && opts.clamp) { - x = Math.min(Math.max(x, lowerBound), upperBound); - x = evenRound(x); - return x; - } + /* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the + * value of this Decimal. + * + * Domain: [1, Infinity] + * Range: [0, Infinity] + * + * acosh(x) = ln(x + sqrt(x^2 - 1)) + * + * acosh(x < 1) = NaN + * acosh(NaN) = NaN + * acosh(Infinity) = Infinity + * acosh(-Infinity) = NaN + * acosh(0) = NaN + * acosh(-0) = NaN + * acosh(1) = 0 + * acosh(-1) = NaN + * + */ + P.inverseHyperbolicCosine = P.acosh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; - if (!Number.isFinite(x) || x === 0) { - return 0; - } - x = integerPart(x); + if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); + if (!x.isFinite()) return new Ctor(x); - // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if - // possible. Hopefully it's an optimization for the non-64-bitLength cases too. - if (x >= lowerBound && x <= upperBound) { - return x; - } + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; + Ctor.rounding = 1; + external = false; - // These will not work great for bitLength of 64, but oh well. See the README for more details. - x = modulo(x, twoToTheBitLength); - if (isSigned && x >= twoToOneLessThanTheBitLength) { - return x - twoToTheBitLength; - } - return x; - }; -} + x = x.times(x).minus(1).sqrt().plus(x); -exports.any = V => { - return V; -}; + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; -exports.void = function () { - return undefined; -}; + return x.ln(); + }; -exports.boolean = function (val) { - return !!val; -}; -exports.byte = createIntegerConversion(8, { unsigned: false }); -exports.octet = createIntegerConversion(8, { unsigned: true }); + /* + * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * asinh(x) = ln(x + sqrt(x^2 + 1)) + * + * asinh(NaN) = NaN + * asinh(Infinity) = Infinity + * asinh(-Infinity) = -Infinity + * asinh(0) = 0 + * asinh(-0) = -0 + * + */ + P.inverseHyperbolicSine = P.asinh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; -exports.short = createIntegerConversion(16, { unsigned: false }); -exports["unsigned short"] = createIntegerConversion(16, { unsigned: true }); + if (!x.isFinite() || x.isZero()) return new Ctor(x); -exports.long = createIntegerConversion(32, { unsigned: false }); -exports["unsigned long"] = createIntegerConversion(32, { unsigned: true }); + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; + Ctor.rounding = 1; + external = false; -exports["long long"] = createIntegerConversion(64, { unsigned: false }); -exports["unsigned long long"] = createIntegerConversion(64, { unsigned: true }); + x = x.times(x).plus(1).sqrt().plus(x); -exports.double = (V, opts) => { - const x = +V; + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; - if (!Number.isFinite(x)) { - throw new TypeError(_("is not a finite floating-point value", opts)); - } + return x.ln(); + }; - return x; -}; -exports["unrestricted double"] = V => { - const x = +V; + /* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the + * value of this Decimal. + * + * Domain: [-1, 1] + * Range: [-Infinity, Infinity] + * + * atanh(x) = 0.5 * ln((1 + x) / (1 - x)) + * + * atanh(|x| > 1) = NaN + * atanh(NaN) = NaN + * atanh(Infinity) = NaN + * atanh(-Infinity) = NaN + * atanh(0) = 0 + * atanh(-0) = -0 + * atanh(1) = Infinity + * atanh(-1) = -Infinity + * + */ + P.inverseHyperbolicTangent = P.atanh = function () { + var pr, rm, wpr, xsd, + x = this, + Ctor = x.constructor; - return x; -}; + if (!x.isFinite()) return new Ctor(NaN); + if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); -exports.float = (V, opts) => { - const x = +V; + pr = Ctor.precision; + rm = Ctor.rounding; + xsd = x.sd(); - if (!Number.isFinite(x)) { - throw new TypeError(_("is not a finite floating-point value", opts)); - } + if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); - if (Object.is(x, -0)) { - return x; - } + Ctor.precision = wpr = xsd - x.e; - const y = Math.fround(x); + x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); - if (!Number.isFinite(y)) { - throw new TypeError(_("is outside the range of a single-precision floating-point value", opts)); - } + Ctor.precision = pr + 4; + Ctor.rounding = 1; - return y; -}; + x = x.ln(); -exports["unrestricted float"] = V => { - const x = +V; + Ctor.precision = pr; + Ctor.rounding = rm; - if (isNaN(x)) { - return x; - } + return x.times(0.5); + }; - if (Object.is(x, -0)) { - return x; - } - return Math.fround(x); -}; + /* + * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2))) + * + * asin(0) = 0 + * asin(-0) = -0 + * asin(1/2) = pi/6 + * asin(-1/2) = -pi/6 + * asin(1) = pi/2 + * asin(-1) = -pi/2 + * asin(|x| > 1) = NaN + * asin(NaN) = NaN + * + * TODO? Compare performance of Taylor series. + * + */ + P.inverseSine = P.asin = function () { + var halfPi, k, + pr, rm, + x = this, + Ctor = x.constructor; -exports.DOMString = function (V, opts) { - if (opts === undefined) { - opts = {}; - } + if (x.isZero()) return new Ctor(x); - if (opts.treatNullAsEmptyString && V === null) { - return ""; - } + k = x.abs().cmp(1); + pr = Ctor.precision; + rm = Ctor.rounding; - if (typeof V === "symbol") { - throw new TypeError(_("is a symbol, which cannot be converted to a string", opts)); - } + if (k !== -1) { - return String(V); -}; + // |x| is 1 + if (k === 0) { + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); + halfPi.s = x.s; + return halfPi; + } -exports.ByteString = (V, opts) => { - const x = exports.DOMString(V, opts); - let c; - for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { - if (c > 255) { - throw new TypeError(_("is not a valid ByteString", opts)); - } + // |x| > 1 or x is NaN + return new Ctor(NaN); } - return x; -}; + // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 -exports.USVString = (V, opts) => { - const S = exports.DOMString(V, opts); - const n = S.length; - const U = []; - for (let i = 0; i < n; ++i) { - const c = S.charCodeAt(i); - if (c < 0xD800 || c > 0xDFFF) { - U.push(String.fromCodePoint(c)); - } else if (0xDC00 <= c && c <= 0xDFFF) { - U.push(String.fromCodePoint(0xFFFD)); - } else if (i === n - 1) { - U.push(String.fromCodePoint(0xFFFD)); - } else { - const d = S.charCodeAt(i + 1); - if (0xDC00 <= d && d <= 0xDFFF) { - const a = c & 0x3FF; - const b = d & 0x3FF; - U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b)); - ++i; - } else { - U.push(String.fromCodePoint(0xFFFD)); - } - } - } + Ctor.precision = pr + 6; + Ctor.rounding = 1; - return U.join(""); -}; + x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); -exports.object = (V, opts) => { - if (type(V) !== "Object") { - throw new TypeError(_("is not an object", opts)); - } + Ctor.precision = pr; + Ctor.rounding = rm; - return V; -}; + return x.times(2); + }; -// Not exported, but used in Function and VoidFunction. -// Neither Function nor VoidFunction is defined with [TreatNonObjectAsNull], so -// handling for that is omitted. -function convertCallbackFunction(V, opts) { - if (typeof V !== "function") { - throw new TypeError(_("is not a function", opts)); + /* + * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + * + * atan(0) = 0 + * atan(-0) = -0 + * atan(1) = pi/4 + * atan(-1) = -pi/4 + * atan(Infinity) = pi/2 + * atan(-Infinity) = -pi/2 + * atan(NaN) = NaN + * + */ + P.inverseTangent = P.atan = function () { + var i, j, k, n, px, t, r, wpr, x2, + x = this, + Ctor = x.constructor, + pr = Ctor.precision, + rm = Ctor.rounding; + + if (!x.isFinite()) { + if (!x.s) return new Ctor(NaN); + if (pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.5); + r.s = x.s; + return r; + } + } else if (x.isZero()) { + return new Ctor(x); + } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.25); + r.s = x.s; + return r; } - return V; -} -const abByteLengthGetter = - Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; + Ctor.precision = wpr = pr + 10; + Ctor.rounding = 1; -function isArrayBuffer(V) { - try { - abByteLengthGetter.call(V); - return true; - } catch (e) { - return false; - } -} + // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); -// I don't think we can reliably detect detached ArrayBuffers. -exports.ArrayBuffer = (V, opts) => { - if (!isArrayBuffer(V)) { - throw new TypeError(_("is not a view on an ArrayBuffer object", opts)); - } - return V; -}; + // Argument reduction + // Ensure |x| < 0.42 + // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) -const dvByteLengthGetter = - Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get; -exports.DataView = (V, opts) => { - try { - dvByteLengthGetter.call(V); - return V; - } catch (e) { - throw new TypeError(_("is not a view on an DataView object", opts)); - } -}; + k = Math.min(28, wpr / LOG_BASE + 2 | 0); -[ - Int8Array, Int16Array, Int32Array, Uint8Array, - Uint16Array, Uint32Array, Uint8ClampedArray, Float32Array, Float64Array -].forEach(func => { - const name = func.name; - const article = /^[AEIOU]/.test(name) ? "an" : "a"; - exports[name] = (V, opts) => { - if (!ArrayBuffer.isView(V) || V.constructor.name !== name) { - throw new TypeError(_(`is not ${article} ${name} object`, opts)); - } + for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); - return V; - }; -}); + external = false; -// Common definitions + j = Math.ceil(wpr / LOG_BASE); + n = 1; + x2 = x.times(x); + r = new Ctor(x); + px = x; -exports.ArrayBufferView = (V, opts) => { - if (!ArrayBuffer.isView(V)) { - throw new TypeError(_("is not a view on an ArrayBuffer object", opts)); - } + // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + for (; i !== -1;) { + px = px.times(x2); + t = r.minus(px.div(n += 2)); - return V; -}; + px = px.times(x2); + r = t.plus(px.div(n += 2)); -exports.BufferSource = (V, opts) => { - if (!ArrayBuffer.isView(V) && !isArrayBuffer(V)) { - throw new TypeError(_("is not an ArrayBuffer object or a view on one", opts)); + if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); } - return V; -}; + if (k) r = r.times(2 << (k - 1)); -exports.DOMTimeStamp = exports["unsigned long long"]; + external = true; -exports.Function = convertCallbackFunction; + return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); + }; -exports.VoidFunction = convertCallbackFunction; + /* + * Return true if the value of this Decimal is a finite number, otherwise return false. + * + */ + P.isFinite = function () { + return !!this.d; + }; -/***/ }), -/***/ 57617: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /* + * Return true if the value of this Decimal is an integer, otherwise return false. + * + */ + P.isInteger = P.isInt = function () { + return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; + }; -"use strict"; -const DOMException = __nccwpck_require__(37561); + /* + * Return true if the value of this Decimal is NaN, otherwise return false. + * + */ + P.isNaN = function () { + return !this.s; + }; -// Special install function to make the DOMException inherit from Error. -// https://heycam.github.io/webidl/#es-DOMException-specialness -function installOverride(globalObject) { - if (typeof globalObject.Error !== "function") { - throw new Error("Internal error: Error constructor is not present on the given global object."); - } - DOMException.install(globalObject); - Object.setPrototypeOf(globalObject.DOMException.prototype, globalObject.Error.prototype); -} + /* + * Return true if the value of this Decimal is negative, otherwise return false. + * + */ + P.isNegative = P.isNeg = function () { + return this.s < 0; + }; -module.exports = {...DOMException, install: installOverride }; + /* + * Return true if the value of this Decimal is positive, otherwise return false. + * + */ + P.isPositive = P.isPos = function () { + return this.s > 0; + }; -/***/ }), -/***/ 49865: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /* + * Return true if the value of this Decimal is 0 or -0, otherwise return false. + * + */ + P.isZero = function () { + return !!this.d && this.d[0] === 0; + }; -var crypto = __nccwpck_require__(76417); -var BigInteger = __nccwpck_require__(85587).BigInteger; -var ECPointFp = __nccwpck_require__(3943).ECPointFp; -var Buffer = __nccwpck_require__(15118).Buffer; -exports.ECCurves = __nccwpck_require__(41452); -// zero prepad -function unstupid(hex,len) -{ - return (hex.length >= len) ? hex : unstupid("0"+hex,len); -} + /* + * Return true if the value of this Decimal is less than `y`, otherwise return false. + * + */ + P.lessThan = P.lt = function (y) { + return this.cmp(y) < 0; + }; -exports.ECKey = function(curve, key, isPublic) -{ - var priv; - var c = curve(); - var n = c.getN(); - var bytes = Math.floor(n.bitLength()/8); - if(key) - { - if(isPublic) - { - var curve = c.getCurve(); -// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format -// var y = key.slice(bytes+1); -// this.P = new ECPointFp(curve, -// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)), -// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16))); - this.P = curve.decodePointHex(key.toString("hex")); - }else{ - if(key.length != bytes) return false; - priv = new BigInteger(key.toString("hex"), 16); - } - }else{ - var n1 = n.subtract(BigInteger.ONE); - var r = new BigInteger(crypto.randomBytes(n.bitLength())); - priv = r.mod(n1).add(BigInteger.ONE); - this.P = c.getG().multiply(priv); - } - if(this.P) - { -// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2); -// this.PublicKey = Buffer.from("04"+pubhex,"hex"); - this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex"); - } - if(priv) - { - this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex"); - this.deriveSharedSecret = function(key) - { - if(!key || !key.P) return false; - var S = key.P.multiply(priv); - return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); - } - } -} + /* + * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. + * + */ + P.lessThanOrEqualTo = P.lte = function (y) { + return this.cmp(y) < 1; + }; + /* + * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * If no base is specified, return log[10](arg). + * + * log[base](arg) = ln(arg) / ln(base) + * + * The result will always be correctly rounded if the base of the log is 10, and 'almost always' + * otherwise: + * + * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen + * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error + * between the result and the correctly rounded result will be one ulp (unit in the last place). + * + * log[-b](a) = NaN + * log[0](a) = NaN + * log[1](a) = NaN + * log[NaN](a) = NaN + * log[Infinity](a) = NaN + * log[b](0) = -Infinity + * log[b](-0) = -Infinity + * log[b](-a) = NaN + * log[b](1) = 0 + * log[b](Infinity) = Infinity + * log[b](NaN) = NaN + * + * [base] {number|string|Decimal} The base of the logarithm. + * + */ + P.logarithm = P.log = function (base) { + var isBase10, d, denominator, k, inf, num, sd, r, + arg = this, + Ctor = arg.constructor, + pr = Ctor.precision, + rm = Ctor.rounding, + guard = 5; + + // Default base is 10. + if (base == null) { + base = new Ctor(10); + isBase10 = true; + } else { + base = new Ctor(base); + d = base.d; -/***/ }), + // Return NaN if base is negative, or non-finite, or is 0 or 1. + if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); -/***/ 3943: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + isBase10 = base.eq(10); + } -// Basic Javascript Elliptic Curve implementation -// Ported loosely from BouncyCastle's Java EC code -// Only Fp curves implemented for now + d = arg.d; -// Requires jsbn.js and jsbn2.js -var BigInteger = __nccwpck_require__(85587).BigInteger -var Barrett = BigInteger.prototype.Barrett + // Is arg negative, non-finite, 0 or 1? + if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { + return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); + } -// ---------------- -// ECFieldElementFp + // The result will have a non-terminating decimal expansion if base is 10 and arg is not an + // integer power of 10. + if (isBase10) { + if (d.length > 1) { + inf = true; + } else { + for (k = d[0]; k % 10 === 0;) k /= 10; + inf = k !== 1; + } + } -// constructor -function ECFieldElementFp(q,x) { - this.x = x; - // TODO if(x.compareTo(q) >= 0) error - this.q = q; -} + external = false; + sd = pr + guard; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); -function feFpEquals(other) { - if(other == this) return true; - return (this.q.equals(other.q) && this.x.equals(other.x)); -} + // The result will have 5 rounding digits. + r = divide(num, denominator, sd, 1); -function feFpToBigInteger() { - return this.x; -} + // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, + // calculate 10 further digits. + // + // If the result is known to have an infinite decimal expansion, repeat this until it is clear + // that the result is above or below the boundary. Otherwise, if after calculating the 10 + // further digits, the last 14 are nines, round up and assume the result is exact. + // Also assume the result is exact if the last 14 are zero. + // + // Example of a result that will be incorrectly rounded: + // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... + // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it + // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so + // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal + // place is still 2.6. + if (checkRoundingDigits(r.d, k = pr, rm)) { -function feFpNegate() { - return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); -} + do { + sd += 10; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); + r = divide(num, denominator, sd, 1); -function feFpAdd(b) { - return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); -} + if (!inf) { -function feFpSubtract(b) { - return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); -} + // Check for 14 nines from the 2nd rounding digit, as the first may be 4. + if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } -function feFpMultiply(b) { - return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); -} + break; + } + } while (checkRoundingDigits(r.d, k += 10, rm)); + } -function feFpSquare() { - return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); -} + external = true; -function feFpDivide(b) { - return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); -} + return finalise(r, pr, rm); + }; -ECFieldElementFp.prototype.equals = feFpEquals; -ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; -ECFieldElementFp.prototype.negate = feFpNegate; -ECFieldElementFp.prototype.add = feFpAdd; -ECFieldElementFp.prototype.subtract = feFpSubtract; -ECFieldElementFp.prototype.multiply = feFpMultiply; -ECFieldElementFp.prototype.square = feFpSquare; -ECFieldElementFp.prototype.divide = feFpDivide; -// ---------------- -// ECPointFp + /* + * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * + P.max = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'lt'); + }; + */ -// constructor -function ECPointFp(curve,x,y,z) { - this.curve = curve; - this.x = x; - this.y = y; - // Projective coordinates: either zinv == null or z * zinv == 1 - // z and zinv are just BigIntegers, not fieldElements - if(z == null) { - this.z = BigInteger.ONE; - } - else { - this.z = z; - } - this.zinv = null; - //TODO: compression flag -} -function pointFpGetX() { - if(this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); - } - var r = this.x.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); -} + /* + * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * + P.min = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'gt'); + }; + */ -function pointFpGetY() { - if(this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); - } - var r = this.y.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); -} -function pointFpEquals(other) { - if(other == this) return true; - if(this.isInfinity()) return other.isInfinity(); - if(other.isInfinity()) return this.isInfinity(); - var u, v; - // u = Y2 * Z1 - Y1 * Z2 - u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); - if(!u.equals(BigInteger.ZERO)) return false; - // v = X2 * Z1 - X1 * Z2 - v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); - return v.equals(BigInteger.ZERO); -} + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.minus = P.sub = function (y) { + var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, + x = this, + Ctor = x.constructor; -function pointFpIsInfinity() { - if((this.x == null) && (this.y == null)) return true; - return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); -} + y = new Ctor(y); -function pointFpNegate() { - return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); -} + // If either is not finite... + if (!x.d || !y.d) { -function pointFpAdd(b) { - if(this.isInfinity()) return b; - if(b.isInfinity()) return this; + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); - // u = Y2 * Z1 - Y1 * Z2 - var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); - // v = X2 * Z1 - X1 * Z2 - var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); + // Return y negated if x is finite and y is ±Infinity. + else if (x.d) y.s = -y.s; - if(BigInteger.ZERO.equals(v)) { - if(BigInteger.ZERO.equals(u)) { - return this.twice(); // this == b, so double - } - return this.curve.getInfinity(); // this = -b, so infinity - } + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with different signs. + // Return NaN if both are ±Infinity with the same sign. + else y = new Ctor(y.d || x.s !== y.s ? x : NaN); - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); - var x2 = b.x.toBigInteger(); - var y2 = b.y.toBigInteger(); + return y; + } - var v2 = v.square(); - var v3 = v2.multiply(v); - var x1v2 = x1.multiply(v2); - var zu2 = u.square().multiply(this.z); + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.plus(y); + } - // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) - var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); - // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 - var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; - return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); -} + // If either is zero... + if (!xd[0] || !yd[0]) { -function pointFpTwice() { - if(this.isInfinity()) return this; - if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); + // Return y negated if x is zero and y is non-zero. + if (yd[0]) y.s = -y.s; - // TODO: optimized handling of constants - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); + // Return x if y is zero and x is non-zero. + else if (xd[0]) y = new Ctor(x); - var y1z1 = y1.multiply(this.z); - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); - var a = this.curve.a.toBigInteger(); + // Return zero if both are zero. + // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. + else return new Ctor(rm === 3 ? -0 : 0); - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE); - if(!BigInteger.ZERO.equals(a)) { - w = w.add(this.z.square().multiply(a)); + return external ? finalise(y, pr, rm) : y; } - w = w.mod(this.curve.q); - //this.curve.reduce(w); - // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) - var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); - // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 - var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); - return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); -} + // x and y are finite, non-zero numbers with the same sign. -// Simple NAF (Non-Adjacent Form) multiplication algorithm -// TODO: modularize the multiplication algorithm -function pointFpMultiply(k) { - if(this.isInfinity()) return this; - if(k.signum() == 0) return this.curve.getInfinity(); + // Calculate base 1e7 exponents. + e = mathfloor(y.e / LOG_BASE); + xe = mathfloor(x.e / LOG_BASE); - var e = k; - var h = e.multiply(new BigInteger("3")); + xd = xd.slice(); + k = xe - e; - var neg = this.negate(); - var R = this; + // If base 1e7 exponents differ... + if (k) { + xLTy = k < 0; - var i; - for(i = h.bitLength() - 2; i > 0; --i) { - R = R.twice(); + if (xLTy) { + d = xd; + k = -k; + len = yd.length; + } else { + d = yd; + e = xe; + len = xd.length; + } - var hBit = h.testBit(i); - var eBit = e.testBit(i); + // Numbers with massively different exponents would result in a very high number of + // zeros needing to be prepended, but this can be avoided while still ensuring correct + // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. + i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; - if (hBit != eBit) { - R = R.add(hBit ? this : neg); - } - } + if (k > i) { + k = i; + d.length = 1; + } - return R; -} + // Prepend zeros to equalise exponents. + d.reverse(); + for (i = k; i--;) d.push(0); + d.reverse(); -// Compute this*j + x*k (simultaneous multiplication) -function pointFpMultiplyTwo(j,x,k) { - var i; - if(j.bitLength() > k.bitLength()) - i = j.bitLength() - 1; - else - i = k.bitLength() - 1; + // Base 1e7 exponents equal. + } else { - var R = this.curve.getInfinity(); - var both = this.add(x); - while(i >= 0) { - R = R.twice(); - if(j.testBit(i)) { - if(k.testBit(i)) { - R = R.add(both); - } - else { - R = R.add(this); - } - } - else { - if(k.testBit(i)) { - R = R.add(x); + // Check digits to determine which is the bigger number. + + i = xd.length; + len = yd.length; + xLTy = i < len; + if (xLTy) len = i; + + for (i = 0; i < len; i++) { + if (xd[i] != yd[i]) { + xLTy = xd[i] < yd[i]; + break; + } } + + k = 0; } - --i; - } - return R; -} + if (xLTy) { + d = xd; + xd = yd; + yd = d; + y.s = -y.s; + } -ECPointFp.prototype.getX = pointFpGetX; -ECPointFp.prototype.getY = pointFpGetY; -ECPointFp.prototype.equals = pointFpEquals; -ECPointFp.prototype.isInfinity = pointFpIsInfinity; -ECPointFp.prototype.negate = pointFpNegate; -ECPointFp.prototype.add = pointFpAdd; -ECPointFp.prototype.twice = pointFpTwice; -ECPointFp.prototype.multiply = pointFpMultiply; -ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; + len = xd.length; -// ---------------- -// ECCurveFp + // Append zeros to `xd` if shorter. + // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. + for (i = yd.length - len; i > 0; --i) xd[len++] = 0; -// constructor -function ECCurveFp(q,a,b) { - this.q = q; - this.a = this.fromBigInteger(a); - this.b = this.fromBigInteger(b); - this.infinity = new ECPointFp(this, null, null); - this.reducer = new Barrett(this.q); -} + // Subtract yd from xd. + for (i = yd.length; i > k;) { -function curveFpGetQ() { - return this.q; -} + if (xd[--i] < yd[i]) { + for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; + --xd[j]; + xd[i] += BASE; + } -function curveFpGetA() { - return this.a; -} + xd[i] -= yd[i]; + } -function curveFpGetB() { - return this.b; -} + // Remove trailing zeros. + for (; xd[--len] === 0;) xd.pop(); -function curveFpEquals(other) { - if(other == this) return true; - return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); -} + // Remove leading zeros and adjust exponent accordingly. + for (; xd[0] === 0; xd.shift()) --e; -function curveFpGetInfinity() { - return this.infinity; -} + // Zero? + if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); -function curveFpFromBigInteger(x) { - return new ECFieldElementFp(this.q, x); -} + y.d = xd; + y.e = getBase10Exponent(xd, e); -function curveReduce(x) { - this.reducer.reduce(x); -} + return external ? finalise(y, pr, rm) : y; + }; -// for now, work with hex strings because they're easier in JS -function curveFpDecodePointHex(s) { - switch(parseInt(s.substr(0,2), 16)) { // first byte - case 0: - return this.infinity; - case 2: - case 3: - // point compression not supported yet - return null; - case 4: - case 6: - case 7: - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len+2, len); - return new ECPointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * The result depends on the modulo mode. + * + */ + P.modulo = P.mod = function (y) { + var q, + x = this, + Ctor = x.constructor; - default: // unsupported - return null; - } -} + y = new Ctor(y); -function curveFpEncodePointHex(p) { - if (p.isInfinity()) return "00"; - var xHex = p.getX().toBigInteger().toString(16); - var yHex = p.getY().toBigInteger().toString(16); - var oLen = this.getQ().toString(16).length; - if ((oLen % 2) != 0) oLen++; - while (xHex.length < oLen) { - xHex = "0" + xHex; - } - while (yHex.length < oLen) { - yHex = "0" + yHex; - } - return "04" + xHex + yHex; -} + // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. + if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); -ECCurveFp.prototype.getQ = curveFpGetQ; -ECCurveFp.prototype.getA = curveFpGetA; -ECCurveFp.prototype.getB = curveFpGetB; -ECCurveFp.prototype.equals = curveFpEquals; -ECCurveFp.prototype.getInfinity = curveFpGetInfinity; -ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; -ECCurveFp.prototype.reduce = curveReduce; -//ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; -ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; + // Return x if y is ±Infinity or x is ±0. + if (!y.d || x.d && !x.d[0]) { + return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); + } -// from: https://github.com/kaielvin/jsbn-ec-point-compression -ECCurveFp.prototype.decodePointHex = function(s) -{ - var yIsEven; - switch(parseInt(s.substr(0,2), 16)) { // first byte - case 0: - return this.infinity; - case 2: - yIsEven = false; - case 3: - if(yIsEven == undefined) yIsEven = true; - var len = s.length - 2; - var xHex = s.substr(2, len); - var x = this.fromBigInteger(new BigInteger(xHex,16)); - var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); - var beta = alpha.sqrt(); + // Prevent rounding of intermediate calculations. + external = false; - if (beta == null) throw "Invalid point compression"; + if (Ctor.modulo == 9) { - var betaValue = beta.toBigInteger(); - if (betaValue.testBit(0) != yIsEven) - { - // Use the other root - beta = this.fromBigInteger(this.getQ().subtract(betaValue)); + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // result = x - q * y where 0 <= result < abs(y) + q = divide(x, y.abs(), 0, 3, 1); + q.s *= y.s; + } else { + q = divide(x, y, 0, Ctor.modulo, 1); } - return new ECPointFp(this,x,beta); - case 4: - case 6: - case 7: - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len+2, len); - return new ECPointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); + q = q.times(y); - default: // unsupported - return null; - } -} -ECCurveFp.prototype.encodeCompressedPointHex = function(p) -{ - if (p.isInfinity()) return "00"; - var xHex = p.getX().toBigInteger().toString(16); - var oLen = this.getQ().toString(16).length; - if ((oLen % 2) != 0) oLen++; - while (xHex.length < oLen) - xHex = "0" + xHex; - var yPrefix; - if(p.getY().toBigInteger().isEven()) yPrefix = "02"; - else yPrefix = "03"; + external = true; - return yPrefix + xHex; -} + return x.minus(q); + }; -ECFieldElementFp.prototype.getR = function() -{ - if(this.r != undefined) return this.r; + /* + * Return a new Decimal whose value is the natural exponential of the value of this Decimal, + * i.e. the base e raised to the power the value of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.naturalExponential = P.exp = function () { + return naturalExponential(this); + }; - this.r = null; - var bitLength = this.q.bitLength(); - if (bitLength > 128) - { - var firstWord = this.q.shiftRight(bitLength - 64); - if (firstWord.intValue() == -1) - { - this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); - } - } - return this.r; -} -ECFieldElementFp.prototype.modMult = function(x1,x2) -{ - return this.modReduce(x1.multiply(x2)); -} -ECFieldElementFp.prototype.modReduce = function(x) -{ - if (this.getR() != null) - { - var qLen = q.bitLength(); - while (x.bitLength() > (qLen + 1)) - { - var u = x.shiftRight(qLen); - var v = x.subtract(u.shiftLeft(qLen)); - if (!this.getR().equals(BigInteger.ONE)) - { - u = u.multiply(this.getR()); - } - x = u.add(v); - } - while (x.compareTo(q) >= 0) - { - x = x.subtract(q); - } - } - else - { - x = x.mod(q); - } - return x; -} -ECFieldElementFp.prototype.sqrt = function() -{ - if (!this.q.testBit(0)) throw "unsupported"; - // p mod 4 == 3 - if (this.q.testBit(1)) - { - var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); - return z.square().equals(this) ? z : null; - } + /* + * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + */ + P.naturalLogarithm = P.ln = function () { + return naturalLogarithm(this); + }; - // p mod 4 == 1 - var qMinusOne = this.q.subtract(BigInteger.ONE); - var legendreExponent = qMinusOne.shiftRight(1); - if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) - { - return null; - } + /* + * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by + * -1. + * + */ + P.negated = P.neg = function () { + var x = new this.constructor(this); + x.s = -x.s; + return finalise(x); + }; - var u = qMinusOne.shiftRight(2); - var k = u.shiftLeft(1).add(BigInteger.ONE); - var Q = this.x; - var fourQ = modDouble(modDouble(Q)); + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.plus = P.add = function (y) { + var carry, d, e, i, k, len, pr, rm, xd, yd, + x = this, + Ctor = x.constructor; - var U, V; - do - { - var P; - do - { - P = new BigInteger(this.q.bitLength(), new SecureRandom()); - } - while (P.compareTo(this.q) >= 0 - || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); + y = new Ctor(y); - var result = this.lucasSequence(P, Q, k); - U = result[0]; - V = result[1]; + // If either is not finite... + if (!x.d || !y.d) { - if (this.modMult(V, V).equals(fourQ)) - { - // Integer division by 2, mod q - if (V.testBit(0)) - { - V = V.add(q); - } + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); - V = V.shiftRight(1); + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with the same sign. + // Return NaN if both are ±Infinity with different signs. + // Return y if x is finite and y is ±Infinity. + else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); - return new ECFieldElementFp(q,V); - } + return y; } - while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); - - return null; -} -ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) -{ - var n = k.bitLength(); - var s = k.getLowestSetBit(); - var Uh = BigInteger.ONE; - var Vl = BigInteger.TWO; - var Vh = P; - var Ql = BigInteger.ONE; - var Qh = BigInteger.ONE; + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.minus(y); + } - for (var j = n - 1; j >= s + 1; --j) - { - Ql = this.modMult(Ql, Qh); + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; - if (k.testBit(j)) - { - Qh = this.modMult(Ql, Q); - Uh = this.modMult(Uh, Vh); - Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); - } - else - { - Qh = Ql; - Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); - Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); - } - } + // If either is zero... + if (!xd[0] || !yd[0]) { - Ql = this.modMult(Ql, Qh); - Qh = this.modMult(Ql, Q); - Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); - Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Ql = this.modMult(Ql, Qh); + // Return x if y is zero. + // Return y if y is non-zero. + if (!yd[0]) y = new Ctor(x); - for (var j = 1; j <= s; ++j) - { - Uh = this.modMult(Uh, Vl); - Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); - Ql = this.modMult(Ql, Ql); + return external ? finalise(y, pr, rm) : y; } - return [ Uh, Vl ]; -} - -var exports = { - ECCurveFp: ECCurveFp, - ECPointFp: ECPointFp, - ECFieldElementFp: ECFieldElementFp -} + // x and y are finite, non-zero numbers with the same sign. -module.exports = exports + // Calculate base 1e7 exponents. + k = mathfloor(x.e / LOG_BASE); + e = mathfloor(y.e / LOG_BASE); + xd = xd.slice(); + i = k - e; -/***/ }), + // If base 1e7 exponents differ... + if (i) { -/***/ 41452: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (i < 0) { + d = xd; + i = -i; + len = yd.length; + } else { + d = yd; + e = k; + len = xd.length; + } -// Named EC curves + // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. + k = Math.ceil(pr / LOG_BASE); + len = k > len ? k + 1 : len + 1; -// Requires ec.js, jsbn.js, and jsbn2.js -var BigInteger = __nccwpck_require__(85587).BigInteger -var ECCurveFp = __nccwpck_require__(3943).ECCurveFp + if (i > len) { + i = len; + d.length = 1; + } + // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. + d.reverse(); + for (; i--;) d.push(0); + d.reverse(); + } -// ---------------- -// X9ECParameters + len = xd.length; + i = yd.length; -// constructor -function X9ECParameters(curve,g,n,h) { - this.curve = curve; - this.g = g; - this.n = n; - this.h = h; -} + // If yd is longer than xd, swap xd and yd so xd points to the longer array. + if (len - i < 0) { + i = len; + d = yd; + yd = xd; + xd = d; + } -function x9getCurve() { - return this.curve; -} + // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. + for (carry = 0; i;) { + carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; + xd[i] %= BASE; + } -function x9getG() { - return this.g; -} + if (carry) { + xd.unshift(carry); + ++e; + } -function x9getN() { - return this.n; -} + // Remove trailing zeros. + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + for (len = xd.length; xd[--len] == 0;) xd.pop(); -function x9getH() { - return this.h; -} + y.d = xd; + y.e = getBase10Exponent(xd, e); -X9ECParameters.prototype.getCurve = x9getCurve; -X9ECParameters.prototype.getG = x9getG; -X9ECParameters.prototype.getN = x9getN; -X9ECParameters.prototype.getH = x9getH; + return external ? finalise(y, pr, rm) : y; + }; -// ---------------- -// SECNamedCurves -function fromHex(s) { return new BigInteger(s, 16); } + /* + * Return the number of significant digits of the value of this Decimal. + * + * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + * + */ + P.precision = P.sd = function (z) { + var k, + x = this; -function secp128r1() { - // p = 2^128 - 2^97 - 1 - var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); - var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); - //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); - var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "161FF7528B899B2D0C28607CA52C5B86" - + "CF5AC8395BAFEB13C02DA292DDED7A83"); - return new X9ECParameters(curve, G, n, h); -} + if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); -function secp160k1() { - // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); - var a = BigInteger.ZERO; - var b = fromHex("7"); - //byte[] S = null; - var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" - + "938CF935318FDCED6BC28286531733C3F03C4FEE"); - return new X9ECParameters(curve, G, n, h); -} + if (x.d) { + k = getPrecision(x.d); + if (z && x.e + 1 > k) k = x.e + 1; + } else { + k = NaN; + } -function secp160r1() { - // p = 2^160 - 2^31 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); - var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); - //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); - var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "4A96B5688EF573284664698968C38BB913CBFC82" - + "23A628553168947D59DCC912042351377AC5FB32"); - return new X9ECParameters(curve, G, n, h); -} + return k; + }; -function secp192k1() { - // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); - var a = BigInteger.ZERO; - var b = fromHex("3"); - //byte[] S = null; - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" - + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); - return new X9ECParameters(curve, G, n, h); -} -function secp192r1() { - // p = 2^192 - 2^64 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); - var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); - //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" - + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); - return new X9ECParameters(curve, G, n, h); -} + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using + * rounding mode `rounding`. + * + */ + P.round = function () { + var x = this, + Ctor = x.constructor; -function secp224r1() { - // p = 2^224 - 2^96 + 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); - var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); - //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" - + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); - return new X9ECParameters(curve, G, n, h); -} + return finalise(new Ctor(x), x.e + 1, Ctor.rounding); + }; -function secp256r1() { - // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 - var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); - var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); - //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); - var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" - + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); - return new X9ECParameters(curve, G, n, h); -} -// TODO: make this into a proper hashtable -function getSECCurveByName(name) { - if(name == "secp128r1") return secp128r1(); - if(name == "secp160k1") return secp160k1(); - if(name == "secp160r1") return secp160r1(); - if(name == "secp192k1") return secp192k1(); - if(name == "secp192r1") return secp192r1(); - if(name == "secp224r1") return secp224r1(); - if(name == "secp256r1") return secp256r1(); - return null; -} + /* + * Return a new Decimal whose value is the sine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * sin(x) = x - x^3/3! + x^5/5! - ... + * + * sin(0) = 0 + * sin(-0) = -0 + * sin(Infinity) = NaN + * sin(-Infinity) = NaN + * sin(NaN) = NaN + * + */ + P.sine = P.sin = function () { + var pr, rm, + x = this, + Ctor = x.constructor; -module.exports = { - "secp128r1":secp128r1, - "secp160k1":secp160k1, - "secp160r1":secp160r1, - "secp192k1":secp192k1, - "secp192r1":secp192r1, - "secp224r1":secp224r1, - "secp256r1":secp256r1 -} + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; -/***/ }), + x = sine(Ctor, toLessThanHalfPi(Ctor, x)); -/***/ 38171: -/***/ ((module) => { + Ctor.precision = pr; + Ctor.rounding = rm; -"use strict"; + return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); + }; -var hasOwn = Object.prototype.hasOwnProperty; -var toStr = Object.prototype.toString; -var defineProperty = Object.defineProperty; -var gOPD = Object.getOwnPropertyDescriptor; + /* + * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + */ + P.squareRoot = P.sqrt = function () { + var m, n, sd, r, rep, t, + x = this, + d = x.d, + e = x.e, + s = x.s, + Ctor = x.constructor; -var isArray = function isArray(arr) { - if (typeof Array.isArray === 'function') { - return Array.isArray(arr); - } + // Negative/NaN/Infinity/zero? + if (s !== 1 || !d || !d[0]) { + return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); + } - return toStr.call(arr) === '[object Array]'; -}; + external = false; -var isPlainObject = function isPlainObject(obj) { - if (!obj || toStr.call(obj) !== '[object Object]') { - return false; - } + // Initial estimate. + s = Math.sqrt(+x); - var hasOwnConstructor = hasOwn.call(obj, 'constructor'); - var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); - // Not own constructor property must be Object - if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { - return false; - } + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = digitsToString(d); - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - var key; - for (key in obj) { /**/ } + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(n); + e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); - return typeof key === 'undefined' || hasOwn.call(obj, key); -}; + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } -// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target -var setProperty = function setProperty(target, options) { - if (defineProperty && options.name === '__proto__') { - defineProperty(target, options.name, { - enumerable: true, - configurable: true, - value: options.newValue, - writable: true - }); - } else { - target[options.name] = options.newValue; - } -}; + r = new Ctor(n); + } else { + r = new Ctor(s.toString()); + } -// Return undefined instead of __proto__ if '__proto__' is not an own property -var getProperty = function getProperty(obj, name) { - if (name === '__proto__') { - if (!hasOwn.call(obj, name)) { - return void 0; - } else if (gOPD) { - // In early versions of node, obj['__proto__'] is buggy when obj has - // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. - return gOPD(obj, name).value; - } - } + sd = (e = Ctor.precision) + 3; - return obj[name]; -}; + // Newton-Raphson iteration. + for (;;) { + t = r; + r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); -module.exports = function extend() { - var options, name, src, copy, copyIsArray, clone; - var target = arguments[0]; - var i = 1; - var length = arguments.length; - var deep = false; + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); - // Handle a deep copy situation - if (typeof target === 'boolean') { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { - target = {}; - } + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or + // 4999, i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { - for (; i < length; ++i) { - options = arguments[i]; - // Only deal with non-null/undefined values - if (options != null) { - // Extend the base object - for (name in options) { - src = getProperty(target, name); - copy = getProperty(options, name); + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); - // Prevent never-ending loop - if (target !== copy) { - // Recurse if we're merging plain objects or arrays - if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && isArray(src) ? src : []; - } else { - clone = src && isPlainObject(src) ? src : {}; - } + if (t.times(t).eq(x)) { + r = t; + break; + } + } - // Never move original objects, clone them - setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); + sd += 4; + rep = 1; + } else { - // Don't bring in undefined values - } else if (typeof copy !== 'undefined') { - setProperty(target, { name: name, newValue: copy }); - } - } - } - } - } + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - // Return the modified object - return target; -}; + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).eq(x); + } + break; + } + } + } -/***/ }), + external = true; -/***/ 87264: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return finalise(r, e, Ctor.rounding, m); + }; -/* - * extsprintf.js: extended POSIX-style sprintf - */ -var mod_assert = __nccwpck_require__(42357); -var mod_util = __nccwpck_require__(31669); + /* + * Return a new Decimal whose value is the tangent of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * tan(0) = 0 + * tan(-0) = -0 + * tan(Infinity) = NaN + * tan(-Infinity) = NaN + * tan(NaN) = NaN + * + */ + P.tangent = P.tan = function () { + var pr, rm, + x = this, + Ctor = x.constructor; -/* - * Public interface - */ -exports.sprintf = jsSprintf; -exports.printf = jsPrintf; -exports.fprintf = jsFprintf; + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); -/* - * Stripped down version of s[n]printf(3c). We make a best effort to throw an - * exception when given a format string we don't understand, rather than - * ignoring it, so that we won't break existing programs if/when we go implement - * the rest of this. - * - * This implementation currently supports specifying - * - field alignment ('-' flag), - * - zero-pad ('0' flag) - * - always show numeric sign ('+' flag), - * - field width - * - conversions for strings, decimal integers, and floats (numbers). - * - argument size specifiers. These are all accepted but ignored, since - * Javascript has no notion of the physical size of an argument. - * - * Everything else is currently unsupported, most notably precision, unsigned - * numbers, non-decimal numbers, and characters. - */ -function jsSprintf(fmt) -{ - var regex = [ - '([^%]*)', /* normal text */ - '%', /* start of format */ - '([\'\\-+ #0]*?)', /* flags (optional) */ - '([1-9]\\d*)?', /* width (optional) */ - '(\\.([1-9]\\d*))?', /* precision (optional) */ - '[lhjztL]*?', /* length mods (ignored) */ - '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ - ].join(''); + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 10; + Ctor.rounding = 1; - var re = new RegExp(regex); - var args = Array.prototype.slice.call(arguments, 1); - var flags, width, precision, conversion; - var left, pad, sign, arg, match; - var ret = ''; - var argn = 1; + x = x.sin(); + x.s = 1; + x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); - mod_assert.equal('string', typeof (fmt)); + Ctor.precision = pr; + Ctor.rounding = rm; - while ((match = re.exec(fmt)) !== null) { - ret += match[1]; - fmt = fmt.substring(match[0].length); + return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); + }; - flags = match[2] || ''; - width = match[3] || 0; - precision = match[4] || ''; - conversion = match[6]; - left = false; - sign = false; - pad = ' '; - if (conversion == '%') { - ret += '%'; - continue; - } + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + */ + P.times = P.mul = function (y) { + var carry, e, i, k, r, rL, t, xdL, ydL, + x = this, + Ctor = x.constructor, + xd = x.d, + yd = (y = new Ctor(y)).d; - if (args.length === 0) - throw (new Error('too few args to sprintf')); + y.s *= x.s; - arg = args.shift(); - argn++; + // If either is NaN, ±Infinity or ±0... + if (!xd || !xd[0] || !yd || !yd[0]) { - if (flags.match(/[\' #]/)) - throw (new Error( - 'unsupported flags: ' + flags)); + return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd - if (precision.length > 0) - throw (new Error( - 'non-zero precision not supported')); + // Return NaN if either is NaN. + // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. + ? NaN - if (flags.match(/-/)) - left = true; + // Return ±Infinity if either is ±Infinity. + // Return ±0 if either is ±0. + : !xd || !yd ? y.s / 0 : y.s * 0); + } - if (flags.match(/0/)) - pad = '0'; + e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); + xdL = xd.length; + ydL = yd.length; - if (flags.match(/\+/)) - sign = true; + // Ensure xd points to the longer array. + if (xdL < ydL) { + r = xd; + xd = yd; + yd = r; + rL = xdL; + xdL = ydL; + ydL = rL; + } - switch (conversion) { - case 's': - if (arg === undefined || arg === null) - throw (new Error('argument ' + argn + - ': attempted to print undefined or null ' + - 'as a string')); - ret += doPad(pad, width, left, arg.toString()); - break; + // Initialise the result array with zeros. + r = []; + rL = xdL + ydL; + for (i = rL; i--;) r.push(0); - case 'd': - arg = Math.floor(arg); - /*jsl:fallthru*/ - case 'f': - sign = sign && arg > 0 ? '+' : ''; - ret += sign + doPad(pad, width, left, - arg.toString()); - break; + // Multiply! + for (i = ydL; --i >= 0;) { + carry = 0; + for (k = xdL + i; k > i;) { + t = r[k] + yd[i] * xd[k - i - 1] + carry; + r[k--] = t % BASE | 0; + carry = t / BASE | 0; + } - case 'x': - ret += doPad(pad, width, left, arg.toString(16)); - break; + r[k] = (r[k] + carry) % BASE | 0; + } - case 'j': /* non-standard */ - if (width === 0) - width = 10; - ret += mod_util.inspect(arg, false, width); - break; + // Remove trailing zeros. + for (; !r[--rL];) r.pop(); - case 'r': /* non-standard */ - ret += dumpException(arg); - break; + if (carry) ++e; + else r.shift(); - default: - throw (new Error('unsupported conversion: ' + - conversion)); - } - } + y.d = r; + y.e = getBase10Exponent(r, e); - ret += fmt; - return (ret); -} + return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; + }; -function jsPrintf() { - var args = Array.prototype.slice.call(arguments); - args.unshift(process.stdout); - jsFprintf.apply(null, args); -} -function jsFprintf(stream) { - var args = Array.prototype.slice.call(arguments, 1); - return (stream.write(jsSprintf.apply(this, args))); -} + /* + * Return a string representing the value of this Decimal in base 2, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toBinary = function (sd, rm) { + return toStringBinary(this, 2, sd, rm); + }; -function doPad(chr, width, left, str) -{ - var ret = str; - while (ret.length < width) { - if (left) - ret += chr; - else - ret = chr + ret; - } + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` + * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. + * + * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toDecimalPlaces = P.toDP = function (dp, rm) { + var x = this, + Ctor = x.constructor; - return (ret); -} + x = new Ctor(x); + if (dp === void 0) return x; -/* - * This function dumps long stack traces for exceptions having a cause() method. - * See node-verror for an example. - */ -function dumpException(ex) -{ - var ret; + checkInt32(dp, 0, MAX_DIGITS); - if (!(ex instanceof Error)) - throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); - /* Note that V8 prepends "ex.stack" with ex.toString(). */ - ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; + return finalise(x, dp + x.e + 1, rm); + }; - if (ex.cause && typeof (ex.cause) === 'function') { - var cex = ex.cause(); - if (cex) { - ret += '\nCaused by: ' + dumpException(cex); - } - } - return (ret); -} + /* + * Return a string representing the value of this Decimal in exponential notation rounded to + * `dp` fixed decimal places using rounding mode `rounding`. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toExponential = function (dp, rm) { + var str, + x = this, + Ctor = x.constructor; + if (dp === void 0) { + str = finiteToString(x, true); + } else { + checkInt32(dp, 0, MAX_DIGITS); -/***/ }), + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); -/***/ 28206: -/***/ ((module) => { + x = finalise(new Ctor(x), dp + 1, rm); + str = finiteToString(x, true, dp + 1); + } -"use strict"; + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; -// do not edit .js files directly - edit src/index.jst + /* + * Return a string representing the value of this Decimal in normal (fixed-point) notation to + * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is + * omitted. + * + * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. + * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. + * (-0).toFixed(3) is '0.000'. + * (-0.5).toFixed(0) is '-0'. + * + */ + P.toFixed = function (dp, rm) { + var str, y, + x = this, + Ctor = x.constructor; + if (dp === void 0) { + str = finiteToString(x); + } else { + checkInt32(dp, 0, MAX_DIGITS); + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); -module.exports = function equal(a, b) { - if (a === b) return true; + y = finalise(new Ctor(x), dp + x.e + 1, rm); + str = finiteToString(y, false, dp + y.e + 1); + } - if (a && b && typeof a == 'object' && typeof b == 'object') { - if (a.constructor !== b.constructor) return false; + // To determine whether to add the minus sign look at the value before it was rounded, + // i.e. look at `x` rather than `y`. + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) - if (!equal(a[i], b[i])) return false; - return true; - } + /* + * Return an array representing the value of this Decimal as a simple fraction with an integer + * numerator and an integer denominator. + * + * The denominator will be a positive non-zero value less than or equal to the specified maximum + * denominator. If a maximum denominator is not specified, the denominator will be the lowest + * value necessary to represent the number exactly. + * + * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity. + * + */ + P.toFraction = function (maxD) { + var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, + x = this, + xd = x.d, + Ctor = x.constructor; + if (!xd) return new Ctor(x); - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + n1 = d0 = new Ctor(1); + d1 = n0 = new Ctor(0); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; + d = new Ctor(d1); + e = d.e = getPrecision(xd) - x.e - 1; + k = e % LOG_BASE; + d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k); - for (i = length; i-- !== 0;) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + if (maxD == null) { - for (i = length; i-- !== 0;) { - var key = keys[i]; + // d is 10**e, the minimum max-denominator needed. + maxD = e > 0 ? d : n1; + } else { + n = new Ctor(maxD); + if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n); + maxD = n.gt(d) ? (e > 0 ? d : n1) : n; + } + + external = false; + n = new Ctor(digitsToString(xd)); + pr = Ctor.precision; + Ctor.precision = e = xd.length * LOG_BASE * 2; + + for (;;) { + q = divide(n, d, 0, 1, 1); + d2 = d0.plus(q.times(d1)); + if (d2.cmp(maxD) == 1) break; + d0 = d1; + d1 = d2; + d2 = n1; + n1 = n0.plus(q.times(d2)); + n0 = d2; + d2 = d; + d = n.minus(q.times(d2)); + n = d2; + } + + d2 = divide(maxD.minus(d0), d1, 0, 1, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + + // Determine which fraction is closer to x, n0/d0 or n1/d1? + r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 + ? [n1, d1] : [n0, d0]; + + Ctor.precision = pr; + external = true; - if (!equal(a[key], b[key])) return false; - } + return r; + }; - return true; - } - // true if both NaN, false otherwise - return a!==a && b!==b; -}; + /* + * Return a string representing the value of this Decimal in base 16, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toHexadecimal = P.toHex = function (sd, rm) { + return toStringBinary(this, 16, sd, rm); + }; -/***/ }), + /* + * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding + * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal. + * + * The return value will always have the same sign as this Decimal, unless either this Decimal + * or `y` is NaN, in which case the return value will be also be NaN. + * + * The return value is not affected by the value of `precision`. + * + * y {number|string|Decimal} The magnitude to round to a multiple of. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toNearest() rounding mode not an integer: {rm}' + * 'toNearest() rounding mode out of range: {rm}' + * + */ + P.toNearest = function (y, rm) { + var x = this, + Ctor = x.constructor; -/***/ 30969: -/***/ ((module) => { + x = new Ctor(x); -"use strict"; + if (y == null) { + // If x is not finite, return x. + if (!x.d) return x; -module.exports = function (data, opts) { - if (!opts) opts = {}; - if (typeof opts === 'function') opts = { cmp: opts }; - var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; + y = new Ctor(1); + rm = Ctor.rounding; + } else { + y = new Ctor(y); + if (rm === void 0) { + rm = Ctor.rounding; + } else { + checkInt32(rm, 0, 8); + } - var cmp = opts.cmp && (function (f) { - return function (node) { - return function (a, b) { - var aobj = { key: a, value: node[a] }; - var bobj = { key: b, value: node[b] }; - return f(aobj, bobj); - }; - }; - })(opts.cmp); + // If x is not finite, return x if y is not NaN, else NaN. + if (!x.d) return y.s ? x : y; - var seen = []; - return (function stringify (node) { - if (node && node.toJSON && typeof node.toJSON === 'function') { - node = node.toJSON(); - } + // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN. + if (!y.d) { + if (y.s) y.s = x.s; + return y; + } + } - if (node === undefined) return; - if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; - if (typeof node !== 'object') return JSON.stringify(node); + // If y is not zero, calculate the nearest multiple of y to x. + if (y.d[0]) { + external = false; + x = divide(x, y, 0, rm, 1).times(y); + external = true; + finalise(x); - var i, out; - if (Array.isArray(node)) { - out = '['; - for (i = 0; i < node.length; i++) { - if (i) out += ','; - out += stringify(node[i]) || 'null'; - } - return out + ']'; - } + // If y is zero, return zero with the sign of x. + } else { + y.s = x.s; + x = y; + } - if (node === null) return 'null'; + return x; + }; - if (seen.indexOf(node) !== -1) { - if (cycles) return JSON.stringify('__cycle__'); - throw new TypeError('Converting circular structure to JSON'); - } - var seenIndex = seen.push(node) - 1; - var keys = Object.keys(node).sort(cmp && cmp(node)); - out = ''; - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = stringify(node[key]); + /* + * Return the value of this Decimal converted to a number primitive. + * Zero keeps its sign. + * + */ + P.toNumber = function () { + return +this; + }; - if (!value) continue; - if (out) out += ','; - out += JSON.stringify(key) + ':' + value; - } - seen.splice(seenIndex, 1); - return '{' + out + '}'; - })(data); -}; + /* + * Return a string representing the value of this Decimal in base 8, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toOctal = function (sd, rm) { + return toStringBinary(this, 8, sd, rm); + }; -/***/ }), -/***/ 31133: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /* + * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded + * to `precision` significant digits using rounding mode `rounding`. + * + * ECMAScript compliant. + * + * pow(x, NaN) = NaN + * pow(x, ±0) = 1 + + * pow(NaN, non-zero) = NaN + * pow(abs(x) > 1, +Infinity) = +Infinity + * pow(abs(x) > 1, -Infinity) = +0 + * pow(abs(x) == 1, ±Infinity) = NaN + * pow(abs(x) < 1, +Infinity) = +0 + * pow(abs(x) < 1, -Infinity) = +Infinity + * pow(+Infinity, y > 0) = +Infinity + * pow(+Infinity, y < 0) = +0 + * pow(-Infinity, odd integer > 0) = -Infinity + * pow(-Infinity, even integer > 0) = +Infinity + * pow(-Infinity, odd integer < 0) = -0 + * pow(-Infinity, even integer < 0) = +0 + * pow(+0, y > 0) = +0 + * pow(+0, y < 0) = +Infinity + * pow(-0, odd integer > 0) = -0 + * pow(-0, even integer > 0) = +0 + * pow(-0, odd integer < 0) = -Infinity + * pow(-0, even integer < 0) = +Infinity + * pow(finite x < 0, finite non-integer) = NaN + * + * For non-integer or very large exponents pow(x, y) is calculated using + * + * x^y = exp(y*ln(x)) + * + * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the + * probability of an incorrectly rounded result + * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14 + * i.e. 1 in 250,000,000,000,000 + * + * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place). + * + * y {number|string|Decimal} The power to which to raise this Decimal. + * + */ + P.toPower = P.pow = function (y) { + var e, k, pr, r, rm, s, + x = this, + Ctor = x.constructor, + yn = +(y = new Ctor(y)); -var debug; + // Either ±Infinity, NaN or ±0? + if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); -module.exports = function () { - if (!debug) { - try { - /* eslint global-require: off */ - debug = __nccwpck_require__(38237)("follow-redirects"); - } - catch (error) { - debug = function () { /* */ }; + x = new Ctor(x); + + if (x.eq(1)) return x; + + pr = Ctor.precision; + rm = Ctor.rounding; + + if (y.eq(1)) return finalise(x, pr, rm); + + // y exponent + e = mathfloor(y.e / LOG_BASE); + + // If y is a small integer use the 'exponentiation by squaring' algorithm. + if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { + r = intPow(Ctor, x, k, pr); + return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); } - } - debug.apply(null, arguments); -}; + s = x.s; -/***/ }), + // if x is negative + if (s < 0) { -/***/ 67707: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // if y is not an integer + if (e < y.d.length - 1) return new Ctor(NaN); -var url = __nccwpck_require__(78835); -var URL = url.URL; -var http = __nccwpck_require__(98605); -var https = __nccwpck_require__(57211); -var Writable = __nccwpck_require__(92413).Writable; -var assert = __nccwpck_require__(42357); -var debug = __nccwpck_require__(31133); + // Result is positive if x is negative and the last digit of integer y is even. + if ((y.d[e] & 1) == 0) s = 1; -// Create handlers that pass events from native requests -var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; -var eventHandlers = Object.create(null); -events.forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; -}); + // if x.eq(-1) + if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) { + x.s = s; + return x; + } + } -// Error types with codes -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded" -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); + // Estimate result exponent. + // x^y = 10^e, where e = y * log10(x) + // log10(x) = log10(x_significand) + x_exponent + // log10(x_significand) = ln(x_significand) / ln(10) + k = mathpow(+x, yn); + e = k == 0 || !isFinite(k) + ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) + : new Ctor(k + '').e; -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; + // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); - } + // Overflow/underflow? + if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0); - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - self._processResponse(response); - }; + external = false; + Ctor.rounding = x.s = 1; - // Perform the first request - this._performRequest(); -} -RedirectableRequest.prototype = Object.create(Writable.prototype); + // Estimate the extra guard digits needed to ensure five correct rounding digits from + // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): + // new Decimal(2.32456).pow('2087987436534566.46411') + // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 + k = Math.min(12, (e + '').length); -RedirectableRequest.prototype.abort = function () { - // Abort the internal request - abortRequest(this._currentRequest); + // r = x^y = exp(y*ln(x)) + r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); - // Abort this request - this.emit("abort"); - this.removeAllListeners(); -}; + // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40) + if (r.d) { -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } + // Truncate to the required precision plus five rounding digits. + r = finalise(r, pr + 5, 1); - // Validate input and shift parameters if necessary - if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } + // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate + // the result. + if (checkRoundingDigits(r.d, pr, rm)) { + e = pr + 10; - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); + // Truncate to the increased precision plus five rounding digits. + r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); + + // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). + if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } + } } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } -}; -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (typeof data === "function") { - callback = data; - data = encoding = null; - } - else if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } + r.s = s; + external = true; + Ctor.rounding = rm; - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } -}; + return finalise(r, pr, rm); + }; -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); -}; + /* + * Return a string representing the value of this Decimal rounded to `sd` significant digits + * using rounding mode `rounding`. + * + * Return exponential notation if `sd` is less than the number of digits necessary to represent + * the integer part of the value in normal notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toPrecision = function (sd, rm) { + var str, + x = this, + Ctor = x.constructor; -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - var self = this; - if (callback) { - this.on("timeout", callback); - } + if (sd === void 0) { + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + } else { + checkInt32(sd, 1, MAX_DIGITS); - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); - } + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); - // Sets up a timer to trigger a timeout event - function startTimer(socket) { - if (self._timeout) { - clearTimeout(self._timeout); + x = finalise(new Ctor(x), sd, rm); + str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd); } - self._timeout = setTimeout(function () { - self.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); - } - // Prevent a timeout from triggering - function clearTimer() { - clearTimeout(this._timeout); - if (callback) { - self.removeListener("timeout", callback); - } - if (!this.socket) { - self._currentRequest.removeListener("socket", startTimer); + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` + * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if + * omitted. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toSD() digits out of range: {sd}' + * 'toSD() digits not an integer: {sd}' + * 'toSD() rounding mode not an integer: {rm}' + * 'toSD() rounding mode out of range: {rm}' + * + */ + P.toSignificantDigits = P.toSD = function (sd, rm) { + var x = this, + Ctor = x.constructor; + + if (sd === void 0) { + sd = Ctor.precision; + rm = Ctor.rounding; + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); } - } - // Start the timer when the socket is opened - if (this.socket) { - startTimer(this.socket); - } - else { - this._currentRequest.once("socket", startTimer); - } + return finalise(new Ctor(x), sd, rm); + }; - this.on("socket", destroyOnTimeout); - this.once("response", clearTimer); - this.once("error", clearTimer); - return this; -}; + /* + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + P.toString = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); -// Proxy all other public ClientRequest methods -[ - "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); + return x.isNeg() && !x.isZero() ? '-' + str : str; }; -}); -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } + /* + * Return a new Decimal whose value is the value of this Decimal truncated to a whole number. + * + */ + P.truncated = P.trunc = function () { + return finalise(new this.constructor(this), this.e + 1, 1); + }; - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } -}; + /* + * Return a string representing the value of this Decimal. + * Unlike `toString`, negative zero will include the minus sign. + * + */ + P.valueOf = P.toJSON = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + return x.isNeg() ? '-' + str : str; + }; -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - this.emit("error", new TypeError("Unsupported protocol " + protocol)); - return; - } - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.substr(0, protocol.length - 1); - this._options.agent = this._options.agents[scheme]; - } + /* + // Add aliases to match BigDecimal method names. + // P.add = P.plus; + P.subtract = P.minus; + P.multiply = P.times; + P.divide = P.div; + P.remainder = P.mod; + P.compareTo = P.cmp; + P.negate = P.neg; + */ - // Create the native request - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - this._currentUrl = url.format(this._options); - // Set up event handlers - request._redirectable = this; - for (var e = 0; e < events.length; e++) { - request.on(events[e], eventHandlers[events[e]]); - } + // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end. - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - /* istanbul ignore else */ - if (request === self._currentRequest) { - // Report any write errors - /* istanbul ignore if */ - if (error) { - self.emit("error", error); - } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - /* istanbul ignore else */ - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } - } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); - } + + /* + * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower, + * finiteToString, naturalExponential, naturalLogarithm + * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest, + * P.toPrecision, P.toSignificantDigits, toStringBinary, random + * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm + * convertBase toStringBinary, parseOther + * cos P.cos + * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy, + * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction, + * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm, + * taylorSeries, atan2, parseOther + * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh, + * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus, + * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot, + * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed, + * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits, + * P.truncated, divide, getLn10, getPi, naturalExponential, + * naturalLogarithm, ceil, floor, round, trunc + * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf, + * toStringBinary + * getBase10Exponent P.minus, P.plus, P.times, parseOther + * getLn10 P.logarithm, naturalLogarithm + * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2 + * getPrecision P.precision, P.toFraction + * getZeroString digitsToString, finiteToString + * intPow P.toPower, parseOther + * isOdd toLessThanHalfPi + * maxOrMin max, min + * naturalExponential P.naturalExponential, P.toPower + * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm, + * P.toPower, naturalExponential + * nonFiniteToString finiteToString, toStringBinary + * parseDecimal Decimal + * parseOther Decimal + * sin P.sin + * taylorSeries P.cosh, P.sinh, cos, sin + * toLessThanHalfPi P.cos, P.sin + * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal + * truncate intPow + * + * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi, + * naturalLogarithm, config, parseOther, random, Decimal + */ + + + function digitsToString(d) { + var i, k, ws, + indexOfLastWord = d.length - 1, + str = '', + w = d[0]; + + if (indexOfLastWord > 0) { + str += w; + for (i = 1; i < indexOfLastWord; i++) { + ws = d[i] + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + str += ws; } - }()); - } -}; -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); + w = d[i]; + ws = w + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + } else if (w === 0) { + return '0'; + } + + // Remove trailing zeros of last w. + for (; w % 10 === 0;) w /= 10; + + return str + w; } - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. - var location = response.headers.location; - if (location && this._options.followRedirects !== false && - statusCode >= 300 && statusCode < 400) { - // Abort the current request - abortRequest(this._currentRequest); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - this.emit("error", new TooManyRedirectsError()); - return; + function checkInt32(i, min, max) { + if (i !== ~~i || i < min || i > max) { + throw Error(invalidArgument + i); } + } - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - // Drop the Host header, as the redirect might lead to a different host - var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) || - url.parse(this._currentUrl).hostname; + /* + * Check 5 rounding digits if `repeating` is null, 4 otherwise. + * `repeating == null` if caller is `log` or `pow`, + * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`. + */ + function checkRoundingDigits(d, i, rm, repeating) { + var di, k, r, rd; - // Create the redirected request - var redirectUrl = url.resolve(this._currentUrl, location); - debug("redirecting to", redirectUrl); - this._isRedirect = true; - var redirectUrlParts = url.parse(redirectUrl); - Object.assign(this._options, redirectUrlParts); + // Get the length of the first word of the array d. + for (k = d[0]; k >= 10; k /= 10) --i; - // Drop the Authorization header if redirecting to another host - if (redirectUrlParts.hostname !== previousHostName) { - removeMatchingHeaders(/^authorization$/i, this._options.headers); + // Is the rounding digit in the first word of d? + if (--i < 0) { + i += LOG_BASE; + di = 0; + } else { + di = Math.ceil((i + 1) / LOG_BASE); + i %= LOG_BASE; } - // Evaluate the beforeRedirect callback - if (typeof this._options.beforeRedirect === "function") { - var responseDetails = { headers: response.headers }; - try { - this._options.beforeRedirect.call(null, this._options, responseDetails); + // i is the index (0 - 6) of the rounding digit. + // E.g. if within the word 3487563 the first rounding digit is 5, + // then i = 4, k = 1000, rd = 3487563 % 1000 = 563 + k = mathpow(10, LOG_BASE - i); + rd = d[di] % k | 0; + + if (repeating == null) { + if (i < 3) { + if (i == 0) rd = rd / 100 | 0; + else if (i == 1) rd = rd / 10 | 0; + r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0; + } else { + r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && + (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || + (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0; } - catch (err) { - this.emit("error", err); - return; + } else { + if (i < 4) { + if (i == 0) rd = rd / 1000 | 0; + else if (i == 1) rd = rd / 100 | 0; + else if (i == 2) rd = rd / 10 | 0; + r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999; + } else { + r = ((repeating || rm < 4) && rd + 1 == k || + (!repeating && rm > 3) && rd + 1 == k / 2) && + (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1; } - this._sanitizeOptions(this._options); - } - - // Perform the redirected request - try { - this._performRequest(); - } - catch (cause) { - var error = new RedirectionError("Redirected request failed: " + cause.message); - error.cause = cause; - this.emit("error", error); } - } - else { - // The response is not a redirect; return it as-is - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - // Clean up - this._requestBodyBuffers = []; + return r; } -}; -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); + // Convert string of `baseIn` to an array of numbers of `baseOut`. + // Eg. convertBase('255', 10, 16) returns [15, 15]. + // Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. + function convertBase(str, baseIn, baseOut) { + var j, + arr = [0], + arrL, + i = 0, + strL = str.length; - // Executes a request, following redirects - function request(input, options, callback) { - // Parse parameters - if (typeof input === "string") { - var urlStr = input; - try { - input = urlToOptions(new URL(urlStr)); - } - catch (err) { - /* istanbul ignore next */ - input = url.parse(urlStr); + for (; i < strL;) { + for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn; + arr[0] += NUMERALS.indexOf(str.charAt(i++)); + for (j = 0; j < arr.length; j++) { + if (arr[j] > baseOut - 1) { + if (arr[j + 1] === void 0) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; } } - else if (URL && (input instanceof URL)) { - input = urlToOptions(input); - } - else { - callback = options; - options = input; - input = { protocol: protocol }; - } - if (typeof options === "function") { - callback = options; - options = null; - } + } - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; + return arr.reverse(); + } - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } - // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } + /* + * cos(x) = 1 - x^2/2! + x^4/4! - ... + * |x| < pi/2 + * + */ + function cosine(Ctor, x) { + var k, y, + len = x.d.length; - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, - }); - }); - return exports; -} + // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1 + // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1 -/* istanbul ignore next */ -function noop() { /* empty */ } + // Estimate the optimum number of times to use the argument reduction. + if (len < 32) { + k = Math.ceil(len / 3); + y = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + y = '2.3283064365386962890625e-10'; + } -// from https://github.com/nodejs/node/blob/master/lib/internal/url.js -function urlToOptions(urlObject) { - var options = { - protocol: urlObject.protocol, - hostname: urlObject.hostname.startsWith("[") ? - /* istanbul ignore next */ - urlObject.hostname.slice(1, -1) : - urlObject.hostname, - hash: urlObject.hash, - search: urlObject.search, - pathname: urlObject.pathname, - path: urlObject.pathname + urlObject.search, - href: urlObject.href, - }; - if (urlObject.port !== "") { - options.port = Number(urlObject.port); - } - return options; -} + Ctor.precision += k; -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; + x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1)); + + // Reverse argument reduction + for (var i = k; i--;) { + var cos2x = x.times(x); + x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1); } - } - return lastValue; -} -function createErrorType(code, defaultMessage) { - function CustomError(message) { - Error.captureStackTrace(this, this.constructor); - this.message = message || defaultMessage; - } - CustomError.prototype = new Error(); - CustomError.prototype.constructor = CustomError; - CustomError.prototype.name = "Error [" + code + "]"; - CustomError.prototype.code = code; - return CustomError; -} + Ctor.precision -= k; -function abortRequest(request) { - for (var e = 0; e < events.length; e++) { - request.removeListener(events[e], eventHandlers[events[e]]); + return x; } - request.on("error", noop); - request.abort(); -} -// Exports -module.exports = wrap({ http: http, https: https }); -module.exports.wrap = wrap; + /* + * Perform division in the specified base. + */ + var divide = (function () { -/***/ }), + // Assumes non-zero x and k, and hence non-zero result. + function multiplyInteger(x, k, base) { + var temp, + carry = 0, + i = x.length; -/***/ 47568: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (x = x.slice(); i--;) { + temp = x[i] * k + carry; + x[i] = temp % base | 0; + carry = temp / base | 0; + } -module.exports = ForeverAgent -ForeverAgent.SSL = ForeverAgentSSL + if (carry) x.unshift(carry); -var util = __nccwpck_require__(31669) - , Agent = __nccwpck_require__(98605).Agent - , net = __nccwpck_require__(11631) - , tls = __nccwpck_require__(4016) - , AgentSSL = __nccwpck_require__(57211).Agent - -function getConnectionName(host, port) { - var name = '' - if (typeof host === 'string') { - name = host + ':' + port - } else { - // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name. - name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':') - } - return name -} + return x; + } -function ForeverAgent(options) { - var self = this - self.options = options || {} - self.requests = {} - self.sockets = {} - self.freeSockets = {} - self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets - self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets - self.on('free', function(socket, host, port) { - var name = getConnectionName(host, port) + function compare(a, b, aL, bL) { + var i, r; - if (self.requests[name] && self.requests[name].length) { - self.requests[name].shift().onSocket(socket) - } else if (self.sockets[name].length < self.minSockets) { - if (!self.freeSockets[name]) self.freeSockets[name] = [] - self.freeSockets[name].push(socket) - - // if an error happens while we don't use the socket anyway, meh, throw the socket away - var onIdleError = function() { - socket.destroy() + if (aL != bL) { + r = aL > bL ? 1 : -1; + } else { + for (i = r = 0; i < aL; i++) { + if (a[i] != b[i]) { + r = a[i] > b[i] ? 1 : -1; + break; + } + } } - socket._onIdleError = onIdleError - socket.on('error', onIdleError) - } else { - // If there are no pending requests just destroy the - // socket and it will get removed from the pool. This - // gets us out of timeout issues and allows us to - // default to Connection:keep-alive. - socket.destroy() + + return r; } - }) -} -util.inherits(ForeverAgent, Agent) + function subtract(a, b, aL, base) { + var i = 0; -ForeverAgent.defaultMinSockets = 5 + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + // Remove leading zeros. + for (; !a[0] && a.length > 1;) a.shift(); + } -ForeverAgent.prototype.createConnection = net.createConnection -ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest -ForeverAgent.prototype.addRequest = function(req, host, port) { - var name = getConnectionName(host, port) - - if (typeof host !== 'string') { - var options = host - port = options.port - host = options.host - } + return function (x, y, pr, rm, dp, base) { + var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, + yL, yz, + Ctor = x.constructor, + sign = x.s == y.s ? 1 : -1, + xd = x.d, + yd = y.d; - if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { - var idleSocket = this.freeSockets[name].pop() - idleSocket.removeListener('error', idleSocket._onIdleError) - delete idleSocket._onIdleError - req._reusedSocket = true - req.onSocket(idleSocket) - } else { - this.addRequestNoreuse(req, host, port) - } -} + // Either NaN, Infinity or 0? + if (!xd || !xd[0] || !yd || !yd[0]) { -ForeverAgent.prototype.removeSocket = function(s, name, host, port) { - if (this.sockets[name]) { - var index = this.sockets[name].indexOf(s) - if (index !== -1) { - this.sockets[name].splice(index, 1) - } - } else if (this.sockets[name] && this.sockets[name].length === 0) { - // don't leak - delete this.sockets[name] - delete this.requests[name] - } - - if (this.freeSockets[name]) { - var index = this.freeSockets[name].indexOf(s) - if (index !== -1) { - this.freeSockets[name].splice(index, 1) - if (this.freeSockets[name].length === 0) { - delete this.freeSockets[name] + return new Ctor(// Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN : + + // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0. + xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0); } - } - } - if (this.requests[name] && this.requests[name].length) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(name, host, port).emit('free') - } -} + if (base) { + logBase = 1; + e = x.e - y.e; + } else { + base = BASE; + logBase = LOG_BASE; + e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase); + } -function ForeverAgentSSL (options) { - ForeverAgent.call(this, options) -} -util.inherits(ForeverAgentSSL, ForeverAgent) + yL = yd.length; + xL = xd.length; + q = new Ctor(sign); + qd = q.d = []; -ForeverAgentSSL.prototype.createConnection = createConnectionSSL -ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest + // Result exponent may be one less than e. + // The digit array of a Decimal from toStringBinary may have trailing zeros. + for (i = 0; yd[i] == (xd[i] || 0); i++); -function createConnectionSSL (port, host, options) { - if (typeof port === 'object') { - options = port; - } else if (typeof host === 'object') { - options = host; - } else if (typeof options === 'object') { - options = options; - } else { - options = {}; - } + if (yd[i] > (xd[i] || 0)) e--; - if (typeof port === 'number') { - options.port = port; - } + if (pr == null) { + sd = pr = Ctor.precision; + rm = Ctor.rounding; + } else if (dp) { + sd = pr + (x.e - y.e) + 1; + } else { + sd = pr; + } - if (typeof host === 'string') { - options.host = host; - } + if (sd < 0) { + qd.push(1); + more = true; + } else { - return tls.connect(options); -} + // Convert precision in number of base 10 digits to base 1e7 digits. + sd = sd / logBase + 2 | 0; + i = 0; + + // divisor < 1e7 + if (yL == 1) { + k = 0; + yd = yd[0]; + sd++; + + // k is the carry. + for (; (i < xL || k) && sd--; i++) { + t = k * base + (xd[i] || 0); + qd[i] = t / yd | 0; + k = t % yd | 0; + } + more = k || i < xL; -/***/ }), + // divisor >= 1e7 + } else { -/***/ 64334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Normalise xd and yd so highest order digit of yd is >= base/2 + k = base / (yd[0] + 1) | 0; -var CombinedStream = __nccwpck_require__(85443); -var util = __nccwpck_require__(31669); -var path = __nccwpck_require__(85622); -var http = __nccwpck_require__(98605); -var https = __nccwpck_require__(57211); -var parseUrl = __nccwpck_require__(78835).parse; -var fs = __nccwpck_require__(35747); -var mime = __nccwpck_require__(43583); -var asynckit = __nccwpck_require__(14812); -var populate = __nccwpck_require__(17142); + if (k > 1) { + yd = multiplyInteger(yd, k, base); + xd = multiplyInteger(xd, k, base); + yL = yd.length; + xL = xd.length; + } -// Public API -module.exports = FormData; + xi = yL; + rem = xd.slice(0, yL); + remL = rem.length; -// make it a Stream -util.inherits(FormData, CombinedStream); + // Add zeros to make remainder as long as divisor. + for (; remL < yL;) rem[remL++] = 0; -/** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. - * - * @constructor - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream - */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(); - } + yz = yd.slice(); + yz.unshift(0); + yd0 = yd[0]; - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; + if (yd[1] >= base / 2) ++yd0; - CombinedStream.call(this); + do { + k = 0; - options = options || {}; - for (var option in options) { - this[option] = options[option]; - } -} + // Compare divisor and remainder. + cmp = compare(yd, rem, yL, remL); -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + // If divisor < remainder. + if (cmp < 0) { -FormData.prototype.append = function(field, value, options) { + // Calculate trial digit, k. + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); - options = options || {}; + // k will be how many times the divisor goes into the current remainder. + k = rem0 / yd0 | 0; - // allow filename as single option - if (typeof options == 'string') { - options = {filename: options}; - } + // Algorithm: + // 1. product = divisor * trial digit (k) + // 2. if product > remainder: product -= divisor, k-- + // 3. remainder -= product + // 4. if product was < remainder at 2: + // 5. compare new remainder and divisor + // 6. If remainder > divisor: remainder -= divisor, k++ - var append = CombinedStream.prototype.append.bind(this); + if (k > 1) { + if (k >= base) k = base - 1; - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; - } + // product = divisor * trial digit. + prod = multiplyInteger(yd, k, base); + prodL = prod.length; + remL = rem.length; - // https://github.com/felixge/node-form-data/issues/38 - if (util.isArray(value)) { - // Please convert your array into string - // the way web server expects it - this._error(new Error('Arrays are not supported.')); - return; - } + // Compare product and remainder. + cmp = compare(prod, rem, prodL, remL); - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); + // product > remainder. + if (cmp == 1) { + k--; - append(header); - append(value); - append(footer); + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yd, prodL, base); + } + } else { - // pass along options.knownLength - this._trackLength(header, value, options); -}; + // cmp is -1. + // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1 + // to avoid it. If k is 1 there is a need to compare yd and rem again below. + if (k == 0) cmp = k = 1; + prod = yd.slice(); + } -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; + prodL = prod.length; + if (prodL < remL) prod.unshift(0); - // used w/ getLengthSync(), when length is known. - // e.g. for streaming directly from a remote server, - // w/ a known file a size, and not wanting to wait for - // incoming file to finish to get its size. - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); - } + // Subtract product from remainder. + subtract(rem, prod, remL, base); - this._valueLength += valueLength; + // If product was < previous remainder. + if (cmp == -1) { + remL = rem.length; - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += - Buffer.byteLength(header) + - FormData.LINE_BREAK.length; + // Compare divisor and new remainder. + cmp = compare(yd, rem, yL, remL); - // empty or either doesn't have path or not an http response - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { - return; - } + // If divisor < new remainder, subtract divisor from remainder. + if (cmp < 1) { + k++; - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yd, remL, base); + } + } -FormData.prototype._lengthRetriever = function(value, callback) { + remL = rem.length; + } else if (cmp === 0) { + k++; + rem = [0]; + } // if cmp === 1, k will be 0 - if (value.hasOwnProperty('fd')) { + // Add the next digit, k, to the result array. + qd[i++] = k; - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { + // Update the remainder. + if (cmp && rem[0]) { + rem[remL++] = xd[xi] || 0; + } else { + rem = [xd[xi]]; + remL = 1; + } - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); + } while ((xi++ < xL || rem[0] !== void 0) && sd--); - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { + more = rem[0] !== void 0; + } - var fileSize; + // Leading zero? + if (!qd[0]) qd.shift(); + } - if (err) { - callback(err); - return; - } + // logBase is 1 when divide is being used for base conversion. + if (logBase == 1) { + q.e = e; + inexact = more; + } else { - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } + // To calculate q.e, first get the number of digits of qd[0]. + for (i = 1, k = qd[0]; k >= 10; k /= 10) i++; + q.e = i + e * logBase - 1; - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); + finalise(q, dp ? pr + q.e + 1 : pr, rm, more); + } - // or request stream http://github.com/mikeal/request - } else if (value.hasOwnProperty('httpModule')) { - // wait till response come back - value.on('response', function(response) { - value.pause(); - callback(null, +response.headers['content-length']); - }); - value.resume(); + return q; + }; + })(); - // something else - } else { - callback('Unknown stream'); - } -}; -FormData.prototype._multiPartHeader = function(field, value, options) { - // custom header specified (as string)? - // it becomes responsible for boundary - // (e.g. to handle extra CRLFs on .NET servers) - if (typeof options.header == 'string') { - return options.header; - } + /* + * Round `x` to `sd` significant digits using rounding mode `rm`. + * Check for over/under-flow. + */ + function finalise(x, sd, rm, isTruncated) { + var digits, i, j, k, rd, roundUp, w, xd, xdi, + Ctor = x.constructor; + + // Don't round if sd is null or undefined. + out: if (sd != null) { + xd = x.d; + + // Infinity/NaN. + if (!xd) return x; + + // rd: the rounding digit, i.e. the digit after the digit that may be rounded up. + // w: the word of xd containing rd, a base 1e7 number. + // xdi: the index of w within xd. + // digits: the number of digits of w. + // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if + // they had leading zeros) + // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero). + + // Get the length of the first word of the digits array xd. + for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++; + i = sd - digits; + + // Is the rounding digit in the first word of xd? + if (i < 0) { + i += LOG_BASE; + j = sd; + w = xd[xdi = 0]; + + // Get the rounding digit at index j of w. + rd = w / mathpow(10, digits - j - 1) % 10 | 0; + } else { + xdi = Math.ceil((i + 1) / LOG_BASE); + k = xd.length; + if (xdi >= k) { + if (isTruncated) { + + // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`. + for (; k++ <= xdi;) xd.push(0); + w = rd = 0; + digits = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + w = k = xd[xdi]; - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); + // Get the number of digits of w. + for (digits = 1; k >= 10; k /= 10) digits++; - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; + // Get the index of rd within w. + i %= LOG_BASE; - // allow custom headers. - if (typeof options.header == 'object') { - populate(headers, options.header); - } + // Get the index of rd within w, adjusted for leading zeros. + // The number of leading zeros of w is given by LOG_BASE - digits. + j = i - LOG_BASE + digits; - var header; - for (var prop in headers) { - if (!headers.hasOwnProperty(prop)) continue; - header = headers[prop]; + // Get the rounding digit at index j of w. + rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0; + } + } - // skip nullish headers. - if (header == null) { - continue; - } + // Are there any non-zero digits after the rounding digit? + isTruncated = isTruncated || sd < 0 || + xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1)); - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } + // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right + // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression + // will give 714. - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; - } - } + roundUp = rm < 4 + ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 && - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); -FormData.prototype._getContentDisposition = function(value, options) { + if (sd < 1 || !xd[0]) { + xd.length = 0; + if (roundUp) { - var filename - , contentDisposition - ; + // Convert sd to decimal places. + sd -= x.e + 1; - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || value.name || value.path) { - // custom filename take precedence - // formidable and the browser add a name property - // fs- and request- streams have path property - filename = path.basename(options.filename || value.name || value.path); - } else if (value.readable && value.hasOwnProperty('httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path); - } + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE); + x.e = -sd || 0; + } else { - if (filename) { - contentDisposition = 'filename="' + filename + '"'; - } + // Zero. + xd[0] = x.e = 0; + } - return contentDisposition; -}; + return x; + } -FormData.prototype._getContentType = function(value, options) { + // Remove excess digits. + if (i == 0) { + xd.length = xdi; + k = 1; + xdi--; + } else { + xd.length = xdi + 1; + k = mathpow(10, LOG_BASE - i); - // use custom content-type above all - var contentType = options.contentType; + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of w. + xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0; + } - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); - } + if (roundUp) { + for (;;) { - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); - } + // Is the digit to be rounded up in the first word of xd? + if (xdi == 0) { - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; - } + // i will be the length of xd[0] before k is added. + for (i = 1, j = xd[0]; j >= 10; j /= 10) i++; + j = xd[0] += k; + for (k = 1; j >= 10; j /= 10) k++; - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xd[0] == BASE) xd[0] = 1; + } - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; - } - - return contentType; -}; - -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; + break; + } else { + xd[xdi] += k; + if (xd[xdi] != BASE) break; + xd[xdi--] = 0; + k = 1; + } + } + } - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); + // Remove trailing zeros. + for (i = xd.length; xd[--i] === 0;) xd.pop(); } - next(footer); - }.bind(this); -}; + if (external) { -FormData.prototype._lastBoundary = function() { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; + // Overflow? + if (x.e > Ctor.maxE) { -FormData.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; + // Infinity. + x.d = null; + x.e = NaN; - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; + // Underflow? + } else if (x.e < Ctor.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + // Ctor.underflow = true; + } // else Ctor.underflow = false; } + + return x; } - return formHeaders; -}; -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); + function finiteToString(x, isExp, sd) { + if (!x.isFinite()) return nonFiniteToString(x); + var k, + e = x.e, + str = digitsToString(x.d), + len = str.length; + + if (isExp) { + if (sd && (k = sd - len) > 0) { + str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k); + } else if (len > 1) { + str = str.charAt(0) + '.' + str.slice(1); + } + + str = str + (x.e < 0 ? 'e' : 'e+') + x.e; + } else if (e < 0) { + str = '0.' + getZeroString(-e - 1) + str; + if (sd && (k = sd - len) > 0) str += getZeroString(k); + } else if (e >= len) { + str += getZeroString(e + 1 - len); + if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k); + } else { + if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k); + if (sd && (k = sd - len) > 0) { + if (e + 1 === len) str += '.'; + str += getZeroString(k); + } + } + + return str; } - return this._boundary; -}; -FormData.prototype._generateBoundary = function() { - // This generates a 50 character boundary similar to those used by Firefox. - // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); + // Calculate the base 10 exponent from the base 1e7 exponent. + function getBase10Exponent(digits, e) { + var w = digits[0]; + + // Add the number of digits of the first word of the digits array. + for ( e *= LOG_BASE; w >= 10; w /= 10) e++; + return e; } - this._boundary = boundary; -}; -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually -// and add it as knownLength option -FormData.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; + function getLn10(Ctor, sd, pr) { + if (sd > LN10_PRECISION) { - // Don't get confused, there are 3 "internal" streams for each keyval pair - // so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; + // Reset global state in case the exception is caught. + external = true; + if (pr) Ctor.precision = pr; + throw Error(precisionLimitExceeded); + } + return finalise(new Ctor(LN10), sd, 1, true); } - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - // Some async length retrievers are present - // therefore synchronous length calculation is false. - // Please use getLength(callback) to get proper length - this._error(new Error('Cannot calculate proper length in synchronous way.')); + + function getPi(Ctor, sd, rm) { + if (sd > PI_PRECISION) throw Error(precisionLimitExceeded); + return finalise(new Ctor(PI), sd, rm, true); } - return knownLength; -}; -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function() { - var hasKnownLength = true; + function getPrecision(digits) { + var w = digits.length - 1, + len = w * LOG_BASE + 1; - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } + w = digits[w]; - return hasKnownLength; -}; + // If non-zero... + if (w) { -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; + // Subtract the number of trailing zeros of the last word. + for (; w % 10 == 0; w /= 10) len--; - if (this._streams.length) { - knownLength += this._lastBoundary().length; + // Add the number of digits of the first word. + for (w = digits[0]; w >= 10; w /= 10) len++; + } + + return len; } - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; + + function getZeroString(k) { + var zs = ''; + for (; k--;) zs += '0'; + return zs; } - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; - } - values.forEach(function(length) { - knownLength += length; - }); + /* + * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an + * integer of type number. + * + * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`. + * + */ + function intPow(Ctor, x, n, pr) { + var isTruncated, + r = new Ctor(1), - cb(null, knownLength); - }); -}; + // Max n of 9007199254740991 takes 53 loop iterations. + // Maximum digits array length; leaves [28, 34] guard digits. + k = Math.ceil(pr / LOG_BASE + 4); -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; + external = false; - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { + for (;;) { + if (n % 2) { + r = r.times(x); + if (truncate(r.d, k)) isTruncated = true; + } - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); + n = mathfloor(n / 2); + if (n === 0) { - // use custom params - } else { + // To ensure correct rounding when r.d is truncated, increment the last word if it is zero. + n = r.d.length - 1; + if (isTruncated && r.d[n] === 0) ++r.d[n]; + break; + } - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; + x = x.times(x); + truncate(x.d, k); } - } - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); + external = true; - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); + return r; } - // get content length and fire away - this.getLength(function(err, length) { - if (err) { - this._error(err); - return; - } - // add content length - request.setHeader('Content-Length', length); + function isOdd(n) { + return n.d[n.d.length - 1] & 1; + } - this.pipe(request); - if (cb) { - request.on('error', cb); - request.on('response', cb.bind(this, null)); - } - }.bind(this)); - return request; -}; + /* + * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'. + */ + function maxOrMin(Ctor, args, ltgt) { + var y, + x = new Ctor(args[0]), + i = 0; + + for (; ++i < args.length;) { + y = new Ctor(args[i]); + if (!y.s) { + x = y; + break; + } else if (x[ltgt](y)) { + x = y; + } + } -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); + return x; } -}; - -FormData.prototype.toString = function () { - return '[object FormData]'; -}; -/***/ }), + /* + * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant + * digits. + * + * Taylor/Maclaurin series. + * + * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ... + * + * Argument reduction: + * Repeat x = x / 32, k += 5, until |x| < 0.1 + * exp(x) = exp(x / 2^k)^(2^k) + * + * Previously, the argument was initially reduced by + * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10) + * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was + * found to be slower than just dividing repeatedly by 32 as above. + * + * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000 + * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000 + * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324) + * + * exp(Infinity) = Infinity + * exp(-Infinity) = 0 + * exp(NaN) = NaN + * exp(±0) = 1 + * + * exp(x) is non-terminating for any finite, non-zero x. + * + * The result will always be correctly rounded. + * + */ + function naturalExponential(x, sd) { + var denominator, guard, j, pow, sum, t, wpr, + rep = 0, + i = 0, + k = 0, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; -/***/ 17142: -/***/ ((module) => { + // 0/NaN/Infinity? + if (!x.d || !x.d[0] || x.e > 17) { -// populates missing values -module.exports = function(dst, src) { + return new Ctor(x.d + ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 + : x.s ? x.s < 0 ? 0 : x : 0 / 0); + } - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } - return dst; -}; + t = new Ctor(0.03125); + // while abs(x) >= 0.1 + while (x.e > -2) { -/***/ }), + // x = x / 2^5 + x = x.times(t); + k += 5; + } -/***/ 13679: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision + // necessary to ensure the first 4 rounding digits are correct. + guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0; + wpr += guard; + denominator = pow = sum = new Ctor(1); + Ctor.precision = wpr; -"use strict"; + for (;;) { + pow = finalise(pow.times(x), wpr, 1); + denominator = denominator.times(++i); + t = sum.plus(divide(pow, denominator, wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + j = k; + while (j--) sum = finalise(sum.times(sum), wpr, 1); + + // Check to see if the first 4 rounding digits are [49]999. + // If so, repeat the summation with a higher precision, otherwise + // e.g. with precision: 18, rounding: 1 + // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123) + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + + if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += 10; + denominator = pow = t = new Ctor(1); + i = 0; + rep++; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } + sum = t; + } + } -module.exports = { - afterRequest: __nccwpck_require__(24391), - beforeRequest: __nccwpck_require__(94440), - browser: __nccwpck_require__(99850), - cache: __nccwpck_require__(77654), - content: __nccwpck_require__(73656), - cookie: __nccwpck_require__(67948), - creator: __nccwpck_require__(33412), - entry: __nccwpck_require__(32525), - har: __nccwpck_require__(84943), - header: __nccwpck_require__(68344), - log: __nccwpck_require__(69142), - page: __nccwpck_require__(29075), - pageTimings: __nccwpck_require__(15096), - postData: __nccwpck_require__(73697), - query: __nccwpck_require__(70877), - request: __nccwpck_require__(92084), - response: __nccwpck_require__(20702), - timings: __nccwpck_require__(36941) -} + /* + * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant + * digits. + * + * ln(-n) = NaN + * ln(0) = -Infinity + * ln(-0) = -Infinity + * ln(1) = 0 + * ln(Infinity) = Infinity + * ln(-Infinity) = NaN + * ln(NaN) = NaN + * + * ln(n) (n != 1) is non-terminating. + * + */ + function naturalLogarithm(y, sd) { + var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2, + n = 1, + guard = 10, + x = y, + xd = x.d, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; -/***/ }), + // Is x negative or Infinity, NaN, 0 or 1? + if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) { + return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x); + } -/***/ 74944: -/***/ ((module) => { + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } -function HARError (errors) { - var message = 'validation failed' + Ctor.precision = wpr += guard; + c = digitsToString(xd); + c0 = c.charAt(0); - this.name = 'HARError' - this.message = message - this.errors = errors + if (Math.abs(e = x.e) < 1.5e15) { - if (typeof Error.captureStackTrace === 'function') { - Error.captureStackTrace(this, this.constructor) - } else { - this.stack = (new Error(message)).stack - } -} + // Argument reduction. + // The series converges faster the closer the argument is to 1, so using + // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b + // multiply the argument by itself until the leading digits of the significand are 7, 8, 9, + // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can + // later be divided by this number, then separate out the power of 10 using + // ln(a*10^b) = ln(a) + b*ln(10). -HARError.prototype = Error.prototype + // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14). + //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) { + // max n is 6 (gives 0.7 - 1.3) + while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) { + x = x.times(y); + c = digitsToString(x.d); + c0 = c.charAt(0); + n++; + } -module.exports = HARError + e = x.e; + if (c0 > 1) { + x = new Ctor('0.' + c); + e++; + } else { + x = new Ctor(c0 + '.' + c.slice(1)); + } + } else { -/***/ }), + // The argument reduction method above may result in overflow if the argument y is a massive + // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this + // function using ln(x*10^e) = ln(x) + e*ln(10). + t = getLn10(Ctor, wpr + 2, pr).times(e + ''); + x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t); + Ctor.precision = pr; -/***/ 75697: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return sd == null ? finalise(x, pr, rm, external = true) : x; + } -var Ajv = __nccwpck_require__(64941) -var HARError = __nccwpck_require__(74944) -var schemas = __nccwpck_require__(13679) + // x1 is x reduced to a value near 1. + x1 = x; -var ajv + // Taylor series. + // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...) + // where x = (y - 1)/(y + 1) (|x| < 1) + sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = 3; -function createAjvInstance () { - var ajv = new Ajv({ - allErrors: true - }) - ajv.addMetaSchema(__nccwpck_require__(81030)) - ajv.addSchema(schemas) + for (;;) { + numerator = finalise(numerator.times(x2), wpr, 1); + t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + sum = sum.times(2); + + // Reverse the argument reduction. Check that e is not 0 because, besides preventing an + // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0. + if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + '')); + sum = divide(sum, new Ctor(n), wpr, 1); + + // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has + // been repeated previously) and the first 4 rounding digits 9999? + // If so, restart the summation with a higher precision, otherwise + // e.g. with precision: 12, rounding: 1 + // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463. + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += guard; + t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = rep = 1; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } - return ajv -} + sum = t; + denominator += 2; + } + } -function validate (name, data) { - data = data || {} - // validator config - ajv = ajv || createAjvInstance() + // ±Infinity, NaN. + function nonFiniteToString(x) { + // Unsigned. + return String(x.s * x.s / 0); + } - var validate = ajv.getSchema(name + '.json') - return new Promise(function (resolve, reject) { - var valid = validate(data) + /* + * Parse the value of a new Decimal `x` from string `str`. + */ + function parseDecimal(x, str) { + var e, i, len; - !valid ? reject(new HARError(validate.errors)) : resolve(data) - }) -} + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); -exports.afterRequest = function (data) { - return validate('afterRequest', data) -} + // Exponential form? + if ((i = str.search(/e/i)) > 0) { -exports.beforeRequest = function (data) { - return validate('beforeRequest', data) -} + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { -exports.browser = function (data) { - return validate('browser', data) -} + // Integer. + e = str.length; + } -exports.cache = function (data) { - return validate('cache', data) -} + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); -exports.content = function (data) { - return validate('content', data) -} + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(len - 1) === 48; --len); + str = str.slice(i, len); -exports.cookie = function (data) { - return validate('cookie', data) -} + if (str) { + len -= i; + x.e = e = e - i - 1; + x.d = []; -exports.creator = function (data) { - return validate('creator', data) -} + // Transform base -exports.entry = function (data) { - return validate('entry', data) -} + // e is the base 10 exponent. + // i is where to slice str to get the first word of the digits array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; -exports.har = function (data) { - return validate('har', data) -} + if (i < len) { + if (i) x.d.push(+str.slice(0, i)); + for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE)); + str = str.slice(i); + i = LOG_BASE - str.length; + } else { + i -= len; + } -exports.header = function (data) { - return validate('header', data) -} + for (; i--;) str += '0'; + x.d.push(+str); -exports.log = function (data) { - return validate('log', data) -} + if (external) { -exports.page = function (data) { - return validate('page', data) -} + // Overflow? + if (x.e > x.constructor.maxE) { -exports.pageTimings = function (data) { - return validate('pageTimings', data) -} + // Infinity. + x.d = null; + x.e = NaN; -exports.postData = function (data) { - return validate('postData', data) -} + // Underflow? + } else if (x.e < x.constructor.minE) { -exports.query = function (data) { - return validate('query', data) -} + // Zero. + x.e = 0; + x.d = [0]; + // x.constructor.underflow = true; + } // else x.constructor.underflow = false; + } + } else { -exports.request = function (data) { - return validate('request', data) -} + // Zero. + x.e = 0; + x.d = [0]; + } -exports.response = function (data) { - return validate('response', data) -} + return x; + } -exports.timings = function (data) { - return validate('timings', data) -} + /* + * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value. + */ + function parseOther(x, str) { + var base, Ctor, divisor, i, isFloat, len, p, xd, xe; -/***/ }), + if (str === 'Infinity' || str === 'NaN') { + if (!+str) x.s = NaN; + x.e = NaN; + x.d = null; + return x; + } -/***/ 31621: -/***/ ((module) => { + if (isHex.test(str)) { + base = 16; + str = str.toLowerCase(); + } else if (isBinary.test(str)) { + base = 2; + } else if (isOctal.test(str)) { + base = 8; + } else { + throw Error(invalidArgument + str); + } -"use strict"; + // Is there a binary exponent part? + i = str.search(/p/i); -module.exports = (flag, argv) => { - argv = argv || process.argv; - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const pos = argv.indexOf(prefix + flag); - const terminatorPos = argv.indexOf('--'); - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); -}; + if (i > 0) { + p = +str.slice(i + 1); + str = str.substring(2, i); + } else { + str = str.slice(2); + } + // Convert `str` as an integer then divide the result by `base` raised to a power such that the + // fraction part will be restored. + i = str.indexOf('.'); + isFloat = i >= 0; + Ctor = x.constructor; -/***/ }), + if (isFloat) { + str = str.replace('.', ''); + len = str.length; + i = len - i; -/***/ 15487: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // log[10](16) = 1.2041... , log[10](88) = 1.9444.... + divisor = intPow(Ctor, new Ctor(base), i, i * 2); + } -"use strict"; + xd = convertBase(str, base, BASE); + xe = xd.length - 1; -const whatwgEncoding = __nccwpck_require__(49967); + // Remove trailing zeros. + for (i = xe; xd[i] === 0; --i) xd.pop(); + if (i < 0) return new Ctor(x.s * 0); + x.e = getBase10Exponent(xd, xe); + x.d = xd; + external = false; -// https://html.spec.whatwg.org/#encoding-sniffing-algorithm -module.exports = (buffer, { transportLayerEncodingLabel, defaultEncoding = "windows-1252" } = {}) => { - let encoding = whatwgEncoding.getBOMEncoding(buffer); // see https://github.com/whatwg/html/issues/1910 + // At what precision to perform the division to ensure exact conversion? + // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount) + // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412 + // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits. + // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount + // Therefore using 4 * the number of digits of str will always be enough. + if (isFloat) x = divide(x, divisor, len * 4); - if (encoding === null && transportLayerEncodingLabel !== undefined) { - encoding = whatwgEncoding.labelToName(transportLayerEncodingLabel); - } + // Multiply by the binary exponent part if present. + if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p)); + external = true; - if (encoding === null) { - encoding = prescanMetaCharset(buffer); + return x; } - if (encoding === null) { - encoding = defaultEncoding; - } - return encoding; -}; + /* + * sin(x) = x - x^3/3! + x^5/5! - ... + * |x| < pi/2 + * + */ + function sine(Ctor, x) { + var k, + len = x.d.length; -// https://html.spec.whatwg.org/multipage/syntax.html#prescan-a-byte-stream-to-determine-its-encoding -function prescanMetaCharset(buffer) { - const l = Math.min(buffer.length, 1024); - for (let i = 0; i < l; i++) { - let c = buffer[i]; - if (c === 0x3C) { - // "<" - const c1 = buffer[i + 1]; - const c2 = buffer[i + 2]; - const c3 = buffer[i + 3]; - const c4 = buffer[i + 4]; - const c5 = buffer[i + 5]; - // !-- (comment start) - if (c1 === 0x21 && c2 === 0x2D && c3 === 0x2D) { - i += 4; - for (; i < l; i++) { - c = buffer[i]; - const cMinus1 = buffer[i - 1]; - const cMinus2 = buffer[i - 2]; - // --> (comment end) - if (c === 0x3E && cMinus1 === 0x2D && cMinus2 === 0x2D) { - break; - } - } - } else if ((c1 === 0x4D || c1 === 0x6D) && - (c2 === 0x45 || c2 === 0x65) && - (c3 === 0x54 || c3 === 0x74) && - (c4 === 0x41 || c4 === 0x61) && - (isSpaceCharacter(c5) || c5 === 0x2F)) { - // "meta" + space or / - i += 6; - const attributeList = new Set(); - let gotPragma = false; - let needPragma = null; - let charset = null; + if (len < 3) return taylorSeries(Ctor, 2, x, x); - let attrRes; - do { - attrRes = getAttribute(buffer, i, l); - if (attrRes.attr && !attributeList.has(attrRes.attr.name)) { - attributeList.add(attrRes.attr.name); - if (attrRes.attr.name === "http-equiv") { - gotPragma = attrRes.attr.value === "content-type"; - } else if (attrRes.attr.name === "content" && !charset) { - charset = extractCharacterEncodingFromMeta(attrRes.attr.value); - if (charset !== null) { - needPragma = true; - } - } else if (attrRes.attr.name === "charset") { - charset = whatwgEncoding.labelToName(attrRes.attr.value); - needPragma = false; - } - } - i = attrRes.i; - } while (attrRes.attr); + // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x) + // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5) + // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20)) - if (needPragma === null) { - continue; - } - if (needPragma === true && gotPragma === false) { - continue; - } - if (charset === null) { - continue; - } + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; - if (charset === "UTF-16LE" || charset === "UTF-16BE") { - charset = "UTF-8"; - } - if (charset === "x-user-defined") { - charset = "windows-1252"; - } + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x); - return charset; - } else if ((c1 >= 0x41 && c1 <= 0x5A) || (c1 >= 0x61 && c1 <= 0x7A)) { - // a-z or A-Z - for (i += 2; i < l; i++) { - c = buffer[i]; - // space or > - if (isSpaceCharacter(c) || c === 0x3E) { - break; - } - } - let attrRes; - do { - attrRes = getAttribute(buffer, i, l); - i = attrRes.i; - } while (attrRes.attr); - } else if (c1 === 0x21 || c1 === 0x2F || c1 === 0x3F) { - // ! or / or ? - for (i += 2; i < l; i++) { - c = buffer[i]; - // > - if (c === 0x3E) { - break; - } - } - } + // Reverse argument reduction + var sin2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sin2_x = x.times(x); + x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20)))); } + + return x; } - return null; -} -// https://html.spec.whatwg.org/multipage/syntax.html#concept-get-attributes-when-sniffing -function getAttribute(buffer, i, l) { - for (; i < l; i++) { - let c = buffer[i]; - // space or / - if (isSpaceCharacter(c) || c === 0x2F) { - continue; - } - // ">" - if (c === 0x3E) { - break; - } - let name = ""; - let value = ""; - nameLoop:for (; i < l; i++) { - c = buffer[i]; - // "=" - if (c === 0x3D && name !== "") { - i++; - break; - } - // space - if (isSpaceCharacter(c)) { - for (i++; i < l; i++) { - c = buffer[i]; - // space - if (isSpaceCharacter(c)) { - continue; - } - // not "=" - if (c !== 0x3D) { - return { attr: { name, value }, i }; - } - i++; - break nameLoop; - } - break; - } - // / or > - if (c === 0x2F || c === 0x3E) { - return { attr: { name, value }, i }; - } - // A-Z - if (c >= 0x41 && c <= 0x5A) { - name += String.fromCharCode(c + 0x20); // lowercase - } else { - name += String.fromCharCode(c); - } - } - c = buffer[i]; - // space - if (isSpaceCharacter(c)) { - for (i++; i < l; i++) { - c = buffer[i]; - // space - if (isSpaceCharacter(c)) { - continue; - } else { - break; - } - } - } - // " or ' - if (c === 0x22 || c === 0x27) { - const quote = c; - for (i++; i < l; i++) { - c = buffer[i]; + // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`. + function taylorSeries(Ctor, n, x, y, isHyperbolic) { + var j, t, u, x2, + i = 1, + pr = Ctor.precision, + k = Math.ceil(pr / LOG_BASE); - if (c === quote) { - i++; - return { attr: { name, value }, i }; - } + external = false; + x2 = x.times(x); + u = new Ctor(y); - // A-Z - if (c >= 0x41 && c <= 0x5A) { - value += String.fromCharCode(c + 0x20); // lowercase - } else { - value += String.fromCharCode(c); - } + for (;;) { + t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1); + u = isHyperbolic ? y.plus(t) : y.minus(t); + y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1); + t = u.plus(y); + + if (t.d[k] !== void 0) { + for (j = k; t.d[j] === u.d[j] && j--;); + if (j == -1) break; } - } - // > - if (c === 0x3E) { - return { attr: { name, value }, i }; + j = u; + u = y; + y = t; + t = j; + i++; } - // A-Z - if (c >= 0x41 && c <= 0x5A) { - value += String.fromCharCode(c + 0x20); // lowercase - } else { - value += String.fromCharCode(c); - } + external = true; + t.d.length = k + 1; - for (i++; i < l; i++) { - c = buffer[i]; + return t; + } - // space or > - if (isSpaceCharacter(c) || c === 0x3E) { - return { attr: { name, value }, i }; - } - // A-Z - if (c >= 0x41 && c <= 0x5A) { - value += String.fromCharCode(c + 0x20); // lowercase - } else { - value += String.fromCharCode(c); - } - } + // Exponent e must be positive and non-zero. + function tinyPow(b, e) { + var n = b; + while (--e) n *= b; + return n; } - return { i }; -} -function extractCharacterEncodingFromMeta(string) { - let position = 0; - while (true) { - const indexOfCharset = string.substring(position).search(/charset/i); + // Return the absolute value of `x` reduced to less than or equal to half pi. + function toLessThanHalfPi(Ctor, x) { + var t, + isNeg = x.s < 0, + pi = getPi(Ctor, Ctor.precision, 1), + halfPi = pi.times(0.5); - if (indexOfCharset === -1) { - return null; - } - let subPosition = position + indexOfCharset + "charset".length; + x = x.abs(); - while (isSpaceCharacter(string[subPosition].charCodeAt(0))) { - ++subPosition; + if (x.lte(halfPi)) { + quadrant = isNeg ? 4 : 1; + return x; } - if (string[subPosition] !== "=") { - position = subPosition - 1; - continue; - } + t = x.divToInt(pi); - ++subPosition; + if (t.isZero()) { + quadrant = isNeg ? 3 : 2; + } else { + x = x.minus(t.times(pi)); - while (isSpaceCharacter(string[subPosition].charCodeAt(0))) { - ++subPosition; + // 0 <= x < pi + if (x.lte(halfPi)) { + quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1); + return x; + } + + quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2); } - position = subPosition; - break; + return x.minus(pi).abs(); } - if (string[position] === "\"" || string[position] === "'") { - const nextIndex = string.indexOf(string[position], position + 1); - if (nextIndex !== -1) { - return whatwgEncoding.labelToName(string.substring(position + 1, nextIndex)); + /* + * Return the value of Decimal `x` as a string in base `baseOut`. + * + * If the optional `sd` argument is present include a binary exponent suffix. + */ + function toStringBinary(x, baseOut, sd, rm) { + var base, e, i, k, len, roundUp, str, xd, y, + Ctor = x.constructor, + isExp = sd !== void 0; + + if (isExp) { + checkInt32(sd, 1, MAX_DIGITS); + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } else { + sd = Ctor.precision; + rm = Ctor.rounding; } - // It is an unmatched quotation mark - return null; - } + if (!x.isFinite()) { + str = nonFiniteToString(x); + } else { + str = finiteToString(x); + i = str.indexOf('.'); - if (string.length === position + 1) { - return null; - } + // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required: + // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10)) + // minBinaryExponent = floor(decimalExponent * log[2](10)) + // log[2](10) = 3.321928094887362347870319429489390175864 - const indexOfASCIIWhitespaceOrSemicolon = string.substring(position + 1).search(/\x09|\x0A|\x0C|\x0D|\x20|;/); - const end = indexOfASCIIWhitespaceOrSemicolon === -1 ? - string.length : - position + indexOfASCIIWhitespaceOrSemicolon + 1; + if (isExp) { + base = 2; + if (baseOut == 16) { + sd = sd * 4 - 3; + } else if (baseOut == 8) { + sd = sd * 3 - 2; + } + } else { + base = baseOut; + } - return whatwgEncoding.labelToName(string.substring(position, end)); -} + // Convert the number as an integer then divide the result by its base raised to a power such + // that the fraction part will be restored. -function isSpaceCharacter(c) { - return c === 0x09 || c === 0x0A || c === 0x0C || c === 0x0D || c === 0x20; -} + // Non-integer. + if (i >= 0) { + str = str.replace('.', ''); + y = new Ctor(1); + y.e = str.length - i; + y.d = convertBase(finiteToString(y), 10, base); + y.e = y.d.length; + } + xd = convertBase(str, 10, base); + e = len = xd.length; -/***/ }), + // Remove trailing zeros. + for (; xd[--len] == 0;) xd.pop(); -/***/ 42479: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!xd[0]) { + str = isExp ? '0p+0' : '0'; + } else { + if (i < 0) { + e--; + } else { + x = new Ctor(x); + x.d = xd; + x.e = e; + x = divide(x, y, sd, rm, 0, base); + xd = x.d; + e = x.e; + roundUp = inexact; + } + + // The rounding digit, i.e. the digit after the digit that may be rounded up. + i = xd[sd]; + k = base / 2; + roundUp = roundUp || xd[sd + 1] !== void 0; + + roundUp = rm < 4 + ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2)) + : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || + rm === (x.s < 0 ? 8 : 7)); + + xd.length = sd; + + if (roundUp) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (; ++xd[--sd] > base - 1;) { + xd[sd] = 0; + if (!sd) { + ++e; + xd.unshift(1); + } + } + } -// Copyright 2015 Joyent, Inc. + // Determine trailing zeros. + for (len = xd.length; !xd[len - 1]; --len); -var parser = __nccwpck_require__(95086); -var signer = __nccwpck_require__(38143); -var verify = __nccwpck_require__(51227); -var utils = __nccwpck_require__(65689); + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]); + // Add binary exponent suffix? + if (isExp) { + if (len > 1) { + if (baseOut == 16 || baseOut == 8) { + i = baseOut == 16 ? 4 : 3; + for (--len; len % i; len++) str += '0'; + xd = convertBase(str, base, baseOut); + for (len = xd.length; !xd[len - 1]; --len); + // xd[0] will always be be 1 + for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]); + } else { + str = str.charAt(0) + '.' + str.slice(1); + } + } -///--- API + str = str + (e < 0 ? 'p' : 'p+') + e; + } else if (e < 0) { + for (; ++e;) str = '0' + str; + str = '0.' + str; + } else { + if (++e > len) for (e -= len; e-- ;) str += '0'; + else if (e < len) str = str.slice(0, e) + '.' + str.slice(e); + } + } -module.exports = { + str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str; + } - parse: parser.parseRequest, - parseRequest: parser.parseRequest, + return x.s < 0 ? '-' + str : str; + } - sign: signer.signRequest, - signRequest: signer.signRequest, - createSigner: signer.createSigner, - isSigner: signer.isSigner, - sshKeyToPEM: utils.sshKeyToPEM, - sshKeyFingerprint: utils.fingerprint, - pemToRsaSSHKey: utils.pemToRsaSSHKey, + // Does not strip trailing zeros. + function truncate(arr, len) { + if (arr.length > len) { + arr.length = len; + return true; + } + } - verify: verify.verifySignature, - verifySignature: verify.verifySignature, - verifyHMAC: verify.verifyHMAC -}; + // Decimal methods -/***/ }), -/***/ 95086: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /* + * abs + * acos + * acosh + * add + * asin + * asinh + * atan + * atanh + * atan2 + * cbrt + * ceil + * clone + * config + * cos + * cosh + * div + * exp + * floor + * hypot + * ln + * log + * log2 + * log10 + * max + * min + * mod + * mul + * pow + * random + * round + * set + * sign + * sin + * sinh + * sqrt + * sub + * tan + * tanh + * trunc + */ -// Copyright 2012 Joyent, Inc. All rights reserved. -var assert = __nccwpck_require__(66631); -var util = __nccwpck_require__(31669); -var utils = __nccwpck_require__(65689); + /* + * Return a new Decimal whose value is the absolute value of `x`. + * + * x {number|string|Decimal} + * + */ + function abs(x) { + return new this(x).abs(); + } + /* + * Return a new Decimal whose value is the arccosine in radians of `x`. + * + * x {number|string|Decimal} + * + */ + function acos(x) { + return new this(x).acos(); + } -///--- Globals -var HASH_ALGOS = utils.HASH_ALGOS; -var PK_ALGOS = utils.PK_ALGOS; -var HttpSignatureError = utils.HttpSignatureError; -var InvalidAlgorithmError = utils.InvalidAlgorithmError; -var validateAlgorithm = utils.validateAlgorithm; + /* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function acosh(x) { + return new this(x).acosh(); + } -var State = { - New: 0, - Params: 1 -}; -var ParamsState = { - Name: 0, - Quote: 1, - Value: 2, - Comma: 3 -}; + /* + * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function add(x, y) { + return new this(x).plus(y); + } -///--- Specific Errors + /* + * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function asin(x) { + return new this(x).asin(); + } -function ExpiredRequestError(message) { - HttpSignatureError.call(this, message, ExpiredRequestError); -} -util.inherits(ExpiredRequestError, HttpSignatureError); + /* + * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function asinh(x) { + return new this(x).asinh(); + } -function InvalidHeaderError(message) { - HttpSignatureError.call(this, message, InvalidHeaderError); -} -util.inherits(InvalidHeaderError, HttpSignatureError); + /* + * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function atan(x) { + return new this(x).atan(); + } -function InvalidParamsError(message) { - HttpSignatureError.call(this, message, InvalidParamsError); -} -util.inherits(InvalidParamsError, HttpSignatureError); + /* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function atanh(x) { + return new this(x).atanh(); + } -function MissingHeaderError(message) { - HttpSignatureError.call(this, message, MissingHeaderError); -} -util.inherits(MissingHeaderError, HttpSignatureError); + /* + * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi + * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi, pi] + * + * y {number|string|Decimal} The y-coordinate. + * x {number|string|Decimal} The x-coordinate. + * + * atan2(±0, -0) = ±pi + * atan2(±0, +0) = ±0 + * atan2(±0, -x) = ±pi for x > 0 + * atan2(±0, x) = ±0 for x > 0 + * atan2(-y, ±0) = -pi/2 for y > 0 + * atan2(y, ±0) = pi/2 for y > 0 + * atan2(±y, -Infinity) = ±pi for finite y > 0 + * atan2(±y, +Infinity) = ±0 for finite y > 0 + * atan2(±Infinity, x) = ±pi/2 for finite x + * atan2(±Infinity, -Infinity) = ±3*pi/4 + * atan2(±Infinity, +Infinity) = ±pi/4 + * atan2(NaN, x) = NaN + * atan2(y, NaN) = NaN + * + */ + function atan2(y, x) { + y = new this(y); + x = new this(x); + var r, + pr = this.precision, + rm = this.rounding, + wpr = pr + 4; + + // Either NaN + if (!y.s || !x.s) { + r = new this(NaN); + + // Both ±Infinity + } else if (!y.d && !x.d) { + r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75); + r.s = y.s; + + // x is ±Infinity or y is ±0 + } else if (!x.d || y.isZero()) { + r = x.s < 0 ? getPi(this, pr, rm) : new this(0); + r.s = y.s; + + // y is ±Infinity or x is ±0 + } else if (!y.d || x.isZero()) { + r = getPi(this, wpr, 1).times(0.5); + r.s = y.s; + + // Both non-zero and finite + } else if (x.s < 0) { + this.precision = wpr; + this.rounding = 1; + r = this.atan(divide(y, x, wpr, 1)); + x = getPi(this, wpr, 1); + this.precision = pr; + this.rounding = rm; + r = y.s < 0 ? r.minus(x) : r.plus(x); + } else { + r = this.atan(divide(y, x, wpr, 1)); + } -function StrictParsingError(message) { - HttpSignatureError.call(this, message, StrictParsingError); -} -util.inherits(StrictParsingError, HttpSignatureError); + return r; + } -///--- Exported API -module.exports = { + /* + * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function cbrt(x) { + return new this(x).cbrt(); + } - /** - * Parses the 'Authorization' header out of an http.ServerRequest object. + + /* + * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`. * - * Note that this API will fully validate the Authorization header, and throw - * on any error. It will not however check the signature, or the keyId format - * as those are specific to your environment. You can use the options object - * to pass in extra constraints. + * x {number|string|Decimal} * - * As a response object you can expect this: + */ + function ceil(x) { + return finalise(x = new this(x), x.e + 1, 2); + } + + + /* + * Configure global settings for a Decimal constructor. * - * { - * "scheme": "Signature", - * "params": { - * "keyId": "foo", - * "algorithm": "rsa-sha256", - * "headers": [ - * "date" or "x-date", - * "digest" - * ], - * "signature": "base64" - * }, - * "signingString": "ready to be passed to crypto.verify()" - * } + * `obj` is an object with one or more of the following properties, + * + * precision {number} + * rounding {number} + * toExpNeg {number} + * toExpPos {number} + * maxE {number} + * minE {number} + * modulo {number} + * crypto {boolean|number} + * defaults {true} + * + * E.g. Decimal.config({ precision: 20, rounding: 4 }) * - * @param {Object} request an http.ServerRequest. - * @param {Object} options an optional options object with: - * - clockSkew: allowed clock skew in seconds (default 300). - * - headers: required header names (def: date or x-date) - * - algorithms: algorithms to support (default: all). - * - strict: should enforce latest spec parsing - * (default: false). - * @return {Object} parsed out object (see above). - * @throws {TypeError} on invalid input. - * @throws {InvalidHeaderError} on an invalid Authorization header error. - * @throws {InvalidParamsError} if the params in the scheme are invalid. - * @throws {MissingHeaderError} if the params indicate a header not present, - * either in the request headers from the params, - * or not in the params from a required header - * in options. - * @throws {StrictParsingError} if old attributes are used in strict parsing - * mode. - * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew. */ - parseRequest: function parseRequest(request, options) { - assert.object(request, 'request'); - assert.object(request.headers, 'request.headers'); - if (options === undefined) { - options = {}; - } - if (options.headers === undefined) { - options.headers = [request.headers['x-date'] ? 'x-date' : 'date']; + function config(obj) { + if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); + var i, p, v, + useDefaults = obj.defaults === true, + ps = [ + 'precision', 1, MAX_DIGITS, + 'rounding', 0, 8, + 'toExpNeg', -EXP_LIMIT, 0, + 'toExpPos', 0, EXP_LIMIT, + 'maxE', 0, EXP_LIMIT, + 'minE', -EXP_LIMIT, 0, + 'modulo', 0, 9 + ]; + + for (i = 0; i < ps.length; i += 3) { + if (p = ps[i], useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; + else throw Error(invalidArgument + p + ': ' + v); + } + } + + if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (v === true || v === false || v === 0 || v === 1) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + this[p] = true; + } else { + throw Error(cryptoUnavailable); + } + } else { + this[p] = false; + } + } else { + throw Error(invalidArgument + p + ': ' + v); + } } - assert.object(options, 'options'); - assert.arrayOfString(options.headers, 'options.headers'); - assert.optionalFinite(options.clockSkew, 'options.clockSkew'); - var authzHeaderName = options.authorizationHeaderName || 'authorization'; + return this; + } - if (!request.headers[authzHeaderName]) { - throw new MissingHeaderError('no ' + authzHeaderName + ' header ' + - 'present in the request'); - } - options.clockSkew = options.clockSkew || 300; + /* + * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function cos(x) { + return new this(x).cos(); + } - var i = 0; - var state = State.New; - var substate = ParamsState.Name; - var tmpName = ''; - var tmpValue = ''; + /* + * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function cosh(x) { + return new this(x).cosh(); + } - var parsed = { - scheme: '', - params: {}, - signingString: '' - }; - var authz = request.headers[authzHeaderName]; - for (i = 0; i < authz.length; i++) { - var c = authz.charAt(i); + /* + * Create and return a Decimal constructor with the same configuration properties as this Decimal + * constructor. + * + */ + function clone(obj) { + var i, p, ps; - switch (Number(state)) { + /* + * The Decimal constructor and exported function. + * Return a new Decimal instance. + * + * v {number|string|Decimal} A numeric value. + * + */ + function Decimal(v) { + var e, i, t, + x = this; - case State.New: - if (c !== ' ') parsed.scheme += c; - else state = State.Params; - break; + // Decimal called without new. + if (!(x instanceof Decimal)) return new Decimal(v); - case State.Params: - switch (Number(substate)) { + // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor + // which points to Object. + x.constructor = Decimal; - case ParamsState.Name: - var code = c.charCodeAt(0); - // restricted name of A-Z / a-z - if ((code >= 0x41 && code <= 0x5a) || // A-Z - (code >= 0x61 && code <= 0x7a)) { // a-z - tmpName += c; - } else if (c === '=') { - if (tmpName.length === 0) - throw new InvalidHeaderError('bad param format'); - substate = ParamsState.Quote; - } else { - throw new InvalidHeaderError('bad param format'); - } - break; + // Duplicate. + if (v instanceof Decimal) { + x.s = v.s; - case ParamsState.Quote: - if (c === '"') { - tmpValue = ''; - substate = ParamsState.Value; - } else { - throw new InvalidHeaderError('bad param format'); - } - break; + if (external) { + if (!v.d || v.e > Decimal.maxE) { - case ParamsState.Value: - if (c === '"') { - parsed.params[tmpName] = tmpValue; - substate = ParamsState.Comma; + // Infinity. + x.e = NaN; + x.d = null; + } else if (v.e < Decimal.minE) { + + // Zero. + x.e = 0; + x.d = [0]; } else { - tmpValue += c; + x.e = v.e; + x.d = v.d.slice(); } - break; + } else { + x.e = v.e; + x.d = v.d ? v.d.slice() : v.d; + } - case ParamsState.Comma: - if (c === ',') { - tmpName = ''; - substate = ParamsState.Name; + return; + } + + t = typeof v; + + if (t === 'number') { + if (v === 0) { + x.s = 1 / v < 0 ? -1 : 1; + x.e = 0; + x.d = [0]; + return; + } + + if (v < 0) { + v = -v; + x.s = -1; + } else { + x.s = 1; + } + + // Fast path for small integers. + if (v === ~~v && v < 1e7) { + for (e = 0, i = v; i >= 10; i /= 10) e++; + + if (external) { + if (e > Decimal.maxE) { + x.e = NaN; + x.d = null; + } else if (e < Decimal.minE) { + x.e = 0; + x.d = [0]; + } else { + x.e = e; + x.d = [v]; + } } else { - throw new InvalidHeaderError('bad param format'); + x.e = e; + x.d = [v]; } - break; - default: - throw new Error('Invalid substate'); + return; + + // Infinity, NaN. + } else if (v * 0 !== 0) { + if (!v) x.s = NaN; + x.e = NaN; + x.d = null; + return; } - break; - default: - throw new Error('Invalid substate'); - } + return parseDecimal(x, v.toString()); - } + } else if (t !== 'string') { + throw Error(invalidArgument + v); + } - if (!parsed.params.headers || parsed.params.headers === '') { - if (request.headers['x-date']) { - parsed.params.headers = ['x-date']; + // Minus sign? + if ((i = v.charCodeAt(0)) === 45) { + v = v.slice(1); + x.s = -1; } else { - parsed.params.headers = ['date']; + // Plus sign? + if (i === 43) v = v.slice(1); + x.s = 1; + } + + return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); + } + + Decimal.prototype = P; + + Decimal.ROUND_UP = 0; + Decimal.ROUND_DOWN = 1; + Decimal.ROUND_CEIL = 2; + Decimal.ROUND_FLOOR = 3; + Decimal.ROUND_HALF_UP = 4; + Decimal.ROUND_HALF_DOWN = 5; + Decimal.ROUND_HALF_EVEN = 6; + Decimal.ROUND_HALF_CEIL = 7; + Decimal.ROUND_HALF_FLOOR = 8; + Decimal.EUCLID = 9; + + Decimal.config = Decimal.set = config; + Decimal.clone = clone; + Decimal.isDecimal = isDecimalInstance; + + Decimal.abs = abs; + Decimal.acos = acos; + Decimal.acosh = acosh; // ES6 + Decimal.add = add; + Decimal.asin = asin; + Decimal.asinh = asinh; // ES6 + Decimal.atan = atan; + Decimal.atanh = atanh; // ES6 + Decimal.atan2 = atan2; + Decimal.cbrt = cbrt; // ES6 + Decimal.ceil = ceil; + Decimal.cos = cos; + Decimal.cosh = cosh; // ES6 + Decimal.div = div; + Decimal.exp = exp; + Decimal.floor = floor; + Decimal.hypot = hypot; // ES6 + Decimal.ln = ln; + Decimal.log = log; + Decimal.log10 = log10; // ES6 + Decimal.log2 = log2; // ES6 + Decimal.max = max; + Decimal.min = min; + Decimal.mod = mod; + Decimal.mul = mul; + Decimal.pow = pow; + Decimal.random = random; + Decimal.round = round; + Decimal.sign = sign; // ES6 + Decimal.sin = sin; + Decimal.sinh = sinh; // ES6 + Decimal.sqrt = sqrt; + Decimal.sub = sub; + Decimal.tan = tan; + Decimal.tanh = tanh; // ES6 + Decimal.trunc = trunc; // ES6 + + if (obj === void 0) obj = {}; + if (obj) { + if (obj.defaults !== true) { + ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto']; + for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; } - } else { - parsed.params.headers = parsed.params.headers.split(' '); } - // Minimally validate the parsed object - if (!parsed.scheme || parsed.scheme !== 'Signature') - throw new InvalidHeaderError('scheme was not "Signature"'); + Decimal.config(obj); - if (!parsed.params.keyId) - throw new InvalidHeaderError('keyId was not specified'); + return Decimal; + } - if (!parsed.params.algorithm) - throw new InvalidHeaderError('algorithm was not specified'); - if (!parsed.params.signature) - throw new InvalidHeaderError('signature was not specified'); + /* + * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function div(x, y) { + return new this(x).div(y); + } - // Check the algorithm against the official list - parsed.params.algorithm = parsed.params.algorithm.toLowerCase(); - try { - validateAlgorithm(parsed.params.algorithm); - } catch (e) { - if (e instanceof InvalidAlgorithmError) - throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' + - 'supported')); - else - throw (e); - } - // Build the signingString - for (i = 0; i < parsed.params.headers.length; i++) { - var h = parsed.params.headers[i].toLowerCase(); - parsed.params.headers[i] = h; + /* + * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The power to which to raise the base of the natural log. + * + */ + function exp(x) { + return new this(x).exp(); + } - if (h === 'request-line') { - if (!options.strict) { - /* - * We allow headers from the older spec drafts if strict parsing isn't - * specified in options. - */ - parsed.signingString += - request.method + ' ' + request.url + ' HTTP/' + request.httpVersion; - } else { - /* Strict parsing doesn't allow older draft headers. */ - throw (new StrictParsingError('request-line is not a valid header ' + - 'with strict parsing enabled.')); - } - } else if (h === '(request-target)') { - parsed.signingString += - '(request-target): ' + request.method.toLowerCase() + ' ' + - request.url; - } else { - var value = request.headers[h]; - if (value === undefined) - throw new MissingHeaderError(h + ' was not in the request'); - parsed.signingString += h + ': ' + value; - } - if ((i + 1) < parsed.params.headers.length) - parsed.signingString += '\n'; - } + /* + * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`. + * + * x {number|string|Decimal} + * + */ + function floor(x) { + return finalise(x = new this(x), x.e + 1, 3); + } - // Check against the constraints - var date; - if (request.headers.date || request.headers['x-date']) { - if (request.headers['x-date']) { - date = new Date(request.headers['x-date']); - } else { - date = new Date(request.headers.date); - } - var now = new Date(); - var skew = Math.abs(now.getTime() - date.getTime()); - if (skew > options.clockSkew * 1000) { - throw new ExpiredRequestError('clock skew of ' + - (skew / 1000) + - 's was greater than ' + - options.clockSkew + 's'); + /* + * Return a new Decimal whose value is the square root of the sum of the squares of the arguments, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...) + * + * arguments {number|string|Decimal} + * + */ + function hypot() { + var i, n, + t = new this(0); + + external = false; + + for (i = 0; i < arguments.length;) { + n = new this(arguments[i++]); + if (!n.d) { + if (n.s) { + external = true; + return new this(1 / 0); + } + t = n; + } else if (t.d) { + t = t.plus(n.times(n)); } } - options.headers.forEach(function (hdr) { - // Remember that we already checked any headers in the params - // were in the request, so if this passes we're good. - if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0) - throw new MissingHeaderError(hdr + ' was not a signed header'); - }); + external = true; - if (options.algorithms) { - if (options.algorithms.indexOf(parsed.params.algorithm) === -1) - throw new InvalidParamsError(parsed.params.algorithm + - ' is not a supported algorithm'); - } + return t.sqrt(); + } - parsed.algorithm = parsed.params.algorithm.toUpperCase(); - parsed.keyId = parsed.params.keyId; - return parsed; + + /* + * Return true if object is a Decimal instance (where Decimal is any Decimal constructor), + * otherwise return false. + * + */ + function isDecimalInstance(obj) { + return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false; } -}; + /* + * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function ln(x) { + return new this(x).ln(); + } -/***/ }), -/***/ 38143: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /* + * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base + * is specified, rounded to `precision` significant digits using rounding mode `rounding`. + * + * log[y](x) + * + * x {number|string|Decimal} The argument of the logarithm. + * y {number|string|Decimal} The base of the logarithm. + * + */ + function log(x, y) { + return new this(x).log(y); + } -// Copyright 2012 Joyent, Inc. All rights reserved. -var assert = __nccwpck_require__(66631); -var crypto = __nccwpck_require__(76417); -var http = __nccwpck_require__(98605); -var util = __nccwpck_require__(31669); -var sshpk = __nccwpck_require__(87022); -var jsprim = __nccwpck_require__(6287); -var utils = __nccwpck_require__(65689); + /* + * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function log2(x) { + return new this(x).log(2); + } -var sprintf = __nccwpck_require__(31669).format; -var HASH_ALGOS = utils.HASH_ALGOS; -var PK_ALGOS = utils.PK_ALGOS; -var InvalidAlgorithmError = utils.InvalidAlgorithmError; -var HttpSignatureError = utils.HttpSignatureError; -var validateAlgorithm = utils.validateAlgorithm; + /* + * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function log10(x) { + return new this(x).log(10); + } -///--- Globals -var AUTHZ_FMT = - 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"'; + /* + * Return a new Decimal whose value is the maximum of the arguments. + * + * arguments {number|string|Decimal} + * + */ + function max() { + return maxOrMin(this, arguments, 'lt'); + } -///--- Specific Errors -function MissingHeaderError(message) { - HttpSignatureError.call(this, message, MissingHeaderError); -} -util.inherits(MissingHeaderError, HttpSignatureError); + /* + * Return a new Decimal whose value is the minimum of the arguments. + * + * arguments {number|string|Decimal} + * + */ + function min() { + return maxOrMin(this, arguments, 'gt'); + } -function StrictParsingError(message) { - HttpSignatureError.call(this, message, StrictParsingError); -} -util.inherits(StrictParsingError, HttpSignatureError); -/* See createSigner() */ -function RequestSigner(options) { - assert.object(options, 'options'); + /* + * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function mod(x, y) { + return new this(x).mod(y); + } - var alg = []; - if (options.algorithm !== undefined) { - assert.string(options.algorithm, 'options.algorithm'); - alg = validateAlgorithm(options.algorithm); + + /* + * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function mul(x, y) { + return new this(x).mul(y); } - this.rs_alg = alg; + /* - * RequestSigners come in two varieties: ones with an rs_signFunc, and ones - * with an rs_signer. + * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The base. + * y {number|string|Decimal} The exponent. * - * rs_signFunc-based RequestSigners have to build up their entire signing - * string within the rs_lines array and give it to rs_signFunc as a single - * concat'd blob. rs_signer-based RequestSigners can add a line at a time to - * their signing state by using rs_signer.update(), thus only needing to - * buffer the hash function state and one line at a time. */ - if (options.sign !== undefined) { - assert.func(options.sign, 'options.sign'); - this.rs_signFunc = options.sign; + function pow(x, y) { + return new this(x).pow(y); + } - } else if (alg[0] === 'hmac' && options.key !== undefined) { - assert.string(options.keyId, 'options.keyId'); - this.rs_keyId = options.keyId; - if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) - throw (new TypeError('options.key for HMAC must be a string or Buffer')); + /* + * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with + * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros + * are produced). + * + * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive. + * + */ + function random(sd) { + var d, e, k, n, + i = 0, + r = new this(1), + rd = []; - /* - * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their - * data in chunks rather than requiring it all to be given in one go - * at the end, so they are more similar to signers than signFuncs. - */ - this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key); - this.rs_signer.sign = function () { - var digest = this.digest('base64'); - return ({ - hashAlgorithm: alg[1], - toString: function () { return (digest); } - }); - }; + if (sd === void 0) sd = this.precision; + else checkInt32(sd, 1, MAX_DIGITS); - } else if (options.key !== undefined) { - var key = options.key; - if (typeof (key) === 'string' || Buffer.isBuffer(key)) - key = sshpk.parsePrivateKey(key); + k = Math.ceil(sd / LOG_BASE); - assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), - 'options.key must be a sshpk.PrivateKey'); - this.rs_key = key; + if (!this.crypto) { + for (; i < k;) rd[i++] = Math.random() * 1e7 | 0; - assert.string(options.keyId, 'options.keyId'); - this.rs_keyId = options.keyId; + // Browsers supporting crypto.getRandomValues. + } else if (crypto.getRandomValues) { + d = crypto.getRandomValues(new Uint32Array(k)); - if (!PK_ALGOS[key.type]) { - throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + - 'keys are not supported')); - } + for (; i < k;) { + n = d[i]; - if (alg[0] !== undefined && key.type !== alg[0]) { - throw (new InvalidAlgorithmError('options.key must be a ' + - alg[0].toUpperCase() + ' key, was given a ' + - key.type.toUpperCase() + ' key instead')); - } + // 0 <= n < 4294967296 + // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865). + if (n >= 4.29e9) { + d[i] = crypto.getRandomValues(new Uint32Array(1))[0]; + } else { - this.rs_signer = key.createSign(alg[1]); + // 0 <= n <= 4289999999 + // 0 <= (n % 1e7) <= 9999999 + rd[i++] = n % 1e7; + } + } - } else { - throw (new TypeError('options.sign (func) or options.key is required')); - } + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { - this.rs_headers = []; - this.rs_lines = []; -} + // buffer + d = crypto.randomBytes(k *= 4); -/** - * Adds a header to be signed, with its value, into this signer. - * - * @param {String} header - * @param {String} value - * @return {String} value written - */ -RequestSigner.prototype.writeHeader = function (header, value) { - assert.string(header, 'header'); - header = header.toLowerCase(); - assert.string(value, 'value'); + for (; i < k;) { - this.rs_headers.push(header); + // 0 <= n < 2147483648 + n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24); - if (this.rs_signFunc) { - this.rs_lines.push(header + ': ' + value); + // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286). + if (n >= 2.14e9) { + crypto.randomBytes(4).copy(d, i); + } else { - } else { - var line = header + ': ' + value; - if (this.rs_headers.length > 0) - line = '\n' + line; - this.rs_signer.update(line); - } + // 0 <= n <= 2139999999 + // 0 <= (n % 1e7) <= 9999999 + rd.push(n % 1e7); + i += 4; + } + } - return (value); -}; + i = k / 4; + } else { + throw Error(cryptoUnavailable); + } -/** - * Adds a default Date header, returning its value. - * - * @return {String} - */ -RequestSigner.prototype.writeDateHeader = function () { - return (this.writeHeader('date', jsprim.rfc1123(new Date()))); -}; + k = rd[--i]; + sd %= LOG_BASE; -/** - * Adds the request target line to be signed. - * - * @param {String} method, HTTP method (e.g. 'get', 'post', 'put') - * @param {String} path - */ -RequestSigner.prototype.writeTarget = function (method, path) { - assert.string(method, 'method'); - assert.string(path, 'path'); - method = method.toLowerCase(); - this.writeHeader('(request-target)', method + ' ' + path); -}; + // Convert trailing digits to zeros according to sd. + if (k && sd) { + n = mathpow(10, LOG_BASE - sd); + rd[i] = (k / n | 0) * n; + } -/** - * Calculate the value for the Authorization header on this request - * asynchronously. - * - * @param {Func} callback (err, authz) - */ -RequestSigner.prototype.sign = function (cb) { - assert.func(cb, 'callback'); + // Remove trailing words which are zero. + for (; rd[i] === 0; i--) rd.pop(); - if (this.rs_headers.length < 1) - throw (new Error('At least one header must be signed')); + // Zero? + if (i < 0) { + e = 0; + rd = [0]; + } else { + e = -1; - var alg, authz; - if (this.rs_signFunc) { - var data = this.rs_lines.join('\n'); - var self = this; - this.rs_signFunc(data, function (err, sig) { - if (err) { - cb(err); - return; - } - try { - assert.object(sig, 'signature'); - assert.string(sig.keyId, 'signature.keyId'); - assert.string(sig.algorithm, 'signature.algorithm'); - assert.string(sig.signature, 'signature.signature'); - alg = validateAlgorithm(sig.algorithm); + // Remove leading words which are zero and adjust exponent accordingly. + for (; rd[0] === 0; e -= LOG_BASE) rd.shift(); - authz = sprintf(AUTHZ_FMT, - sig.keyId, - sig.algorithm, - self.rs_headers.join(' '), - sig.signature); - } catch (e) { - cb(e); - return; - } - cb(null, authz); - }); + // Count the digits of the first word of rd to determine leading zeros. + for (k = 1, n = rd[0]; n >= 10; n /= 10) k++; - } else { - try { - var sigObj = this.rs_signer.sign(); - } catch (e) { - cb(e); - return; + // Adjust the exponent for leading zeros of the first word of rd. + if (k < LOG_BASE) e -= LOG_BASE - k; } - alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm; - var signature = sigObj.toString(); - authz = sprintf(AUTHZ_FMT, - this.rs_keyId, - alg, - this.rs_headers.join(' '), - signature); - cb(null, authz); + + r.e = e; + r.d = rd; + + return r; } -}; -///--- Exported API -module.exports = { - /** - * Identifies whether a given object is a request signer or not. + /* + * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`. + * + * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL). + * + * x {number|string|Decimal} * - * @param {Object} object, the object to identify - * @returns {Boolean} */ - isSigner: function (obj) { - if (typeof (obj) === 'object' && obj instanceof RequestSigner) - return (true); - return (false); - }, + function round(x) { + return finalise(x = new this(x), x.e + 1, this.rounding); + } - /** - * Creates a request signer, used to asynchronously build a signature - * for a request (does not have to be an http.ClientRequest). + + /* + * Return + * 1 if x > 0, + * -1 if x < 0, + * 0 if x is 0, + * -0 if x is -0, + * NaN otherwise + * + * x {number|string|Decimal} * - * @param {Object} options, either: - * - {String} keyId - * - {String|Buffer} key - * - {String} algorithm (optional, required for HMAC) - * or: - * - {Func} sign (data, cb) - * @return {RequestSigner} */ - createSigner: function createSigner(options) { - return (new RequestSigner(options)); - }, + function sign(x) { + x = new this(x); + return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN; + } - /** - * Adds an 'Authorization' header to an http.ClientRequest object. + + /* + * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits + * using rounding mode `rounding`. * - * Note that this API will add a Date header if it's not already set. Any - * other headers in the options.headers array MUST be present, or this - * will throw. + * x {number|string|Decimal} A value in radians. * - * You shouldn't need to check the return type; it's just there if you want - * to be pedantic. + */ + function sin(x) { + return new this(x).sin(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. * - * The optional flag indicates whether parsing should use strict enforcement - * of the version draft-cavage-http-signatures-04 of the spec or beyond. - * The default is to be loose and support - * older versions for compatibility. + * x {number|string|Decimal} A value in radians. * - * @param {Object} request an instance of http.ClientRequest. - * @param {Object} options signing parameters object: - * - {String} keyId required. - * - {String} key required (either a PEM or HMAC key). - * - {Array} headers optional; defaults to ['date']. - * - {String} algorithm optional (unless key is HMAC); - * default is the same as the sshpk default - * signing algorithm for the type of key given - * - {String} httpVersion optional; defaults to '1.1'. - * - {Boolean} strict optional; defaults to 'false'. - * @return {Boolean} true if Authorization (and optionally Date) were added. - * @throws {TypeError} on bad parameter types (input). - * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with - * the given key. - * @throws {sshpk.KeyParseError} if key was bad. - * @throws {MissingHeaderError} if a header to be signed was specified but - * was not present. */ - signRequest: function signRequest(request, options) { - assert.object(request, 'request'); - assert.object(options, 'options'); - assert.optionalString(options.algorithm, 'options.algorithm'); - assert.string(options.keyId, 'options.keyId'); - assert.optionalArrayOfString(options.headers, 'options.headers'); - assert.optionalString(options.httpVersion, 'options.httpVersion'); + function sinh(x) { + return new this(x).sinh(); + } - if (!request.getHeader('Date')) - request.setHeader('Date', jsprim.rfc1123(new Date())); - if (!options.headers) - options.headers = ['date']; - if (!options.httpVersion) - options.httpVersion = '1.1'; - var alg = []; - if (options.algorithm) { - options.algorithm = options.algorithm.toLowerCase(); - alg = validateAlgorithm(options.algorithm); - } + /* + * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function sqrt(x) { + return new this(x).sqrt(); + } - var i; - var stringToSign = ''; - for (i = 0; i < options.headers.length; i++) { - if (typeof (options.headers[i]) !== 'string') - throw new TypeError('options.headers must be an array of Strings'); - var h = options.headers[i].toLowerCase(); + /* + * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function sub(x, y) { + return new this(x).sub(y); + } - if (h === 'request-line') { - if (!options.strict) { - /** - * We allow headers from the older spec drafts if strict parsing isn't - * specified in options. - */ - stringToSign += - request.method + ' ' + request.path + ' HTTP/' + - options.httpVersion; - } else { - /* Strict parsing doesn't allow older draft headers. */ - throw (new StrictParsingError('request-line is not a valid header ' + - 'with strict parsing enabled.')); - } - } else if (h === '(request-target)') { - stringToSign += - '(request-target): ' + request.method.toLowerCase() + ' ' + - request.path; - } else { - var value = request.getHeader(h); - if (value === undefined || value === '') { - throw new MissingHeaderError(h + ' was not in the request'); - } - stringToSign += h + ': ' + value; - } - if ((i + 1) < options.headers.length) - stringToSign += '\n'; - } + /* + * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function tan(x) { + return new this(x).tan(); + } - /* This is just for unit tests. */ - if (request.hasOwnProperty('_stringToSign')) { - request._stringToSign = stringToSign; - } - var signature; - if (alg[0] === 'hmac') { - if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) - throw (new TypeError('options.key must be a string or Buffer')); + /* + * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function tanh(x) { + return new this(x).tanh(); + } - var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key); - hmac.update(stringToSign); - signature = hmac.digest('base64'); - } else { - var key = options.key; - if (typeof (key) === 'string' || Buffer.isBuffer(key)) - key = sshpk.parsePrivateKey(options.key); + /* + * Return a new Decimal whose value is `x` truncated to an integer. + * + * x {number|string|Decimal} + * + */ + function trunc(x) { + return finalise(x = new this(x), x.e + 1, 1); + } - assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), - 'options.key must be a sshpk.PrivateKey'); - if (!PK_ALGOS[key.type]) { - throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + - 'keys are not supported')); - } + // Create and configure initial Decimal constructor. + Decimal = clone(DEFAULTS); - if (alg[0] !== undefined && key.type !== alg[0]) { - throw (new InvalidAlgorithmError('options.key must be a ' + - alg[0].toUpperCase() + ' key, was given a ' + - key.type.toUpperCase() + ' key instead')); - } + Decimal['default'] = Decimal.Decimal = Decimal; - var signer = key.createSign(alg[1]); - signer.update(stringToSign); - var sigObj = signer.sign(); - if (!HASH_ALGOS[sigObj.hashAlgorithm]) { - throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() + - ' is not a supported hash algorithm')); - } - options.algorithm = key.type + '-' + sigObj.hashAlgorithm; - signature = sigObj.toString(); - assert.notStrictEqual(signature, '', 'empty signature produced'); + // Create the internal constants from their string values. + LN10 = new Decimal(LN10); + PI = new Decimal(PI); + + + // Export. + + + // AMD. + if (typeof define == 'function' && define.amd) { + define(function () { + return Decimal; + }); + + // Node and other environments that support module.exports. + } else if ( true && module.exports) { + if (typeof Symbol == 'function' && typeof Symbol.iterator == 'symbol') { + P[Symbol.for('nodejs.util.inspect.custom')] = P.toString; + P[Symbol.toStringTag] = 'Decimal'; } - var authzHeaderName = options.authorizationHeaderName || 'Authorization'; + module.exports = Decimal; - request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT, - options.keyId, - options.algorithm, - options.headers.join(' '), - signature)); + // Browser. + } else { + if (!globalScope) { + globalScope = typeof self != 'undefined' && self && self.self == self ? self : window; + } - return true; - } + noConflict = globalScope.Decimal; + Decimal.noConflict = function () { + globalScope.Decimal = noConflict; + return Decimal; + }; -}; + globalScope.Decimal = Decimal; + } +})(this); /***/ }), -/***/ 65689: +/***/ 18611: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright 2012 Joyent, Inc. All rights reserved. +var Stream = (__nccwpck_require__(12781).Stream); +var util = __nccwpck_require__(73837); -var assert = __nccwpck_require__(66631); -var sshpk = __nccwpck_require__(87022); -var util = __nccwpck_require__(31669); +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; -var HASH_ALGOS = { - 'sha1': true, - 'sha256': true, - 'sha512': true -}; + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); -var PK_ALGOS = { - 'rsa': true, - 'dsa': true, - 'ecdsa': true -}; +DelayedStream.create = function(source, options) { + var delayedStream = new this(); -function HttpSignatureError(message, caller) { - if (Error.captureStackTrace) - Error.captureStackTrace(this, caller || HttpSignatureError); + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; + } - this.message = message; - this.name = caller.name; -} -util.inherits(HttpSignatureError, Error); + delayedStream.source = source; -function InvalidAlgorithmError(message) { - HttpSignatureError.call(this, message, InvalidAlgorithmError); -} -util.inherits(InvalidAlgorithmError, HttpSignatureError); + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; -function validateAlgorithm(algorithm) { - var alg = algorithm.toLowerCase().split('-'); + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); + } - if (alg.length !== 2) { - throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' + - 'valid algorithm')); + return delayedStream; +}; + +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; } +}); - if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) { - throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' + - 'are not supported')); +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; + +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); } - if (!HASH_ALGOS[alg[1]]) { - throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' + - 'supported hash algorithm')); + this.source.resume(); +}; + +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; + +DelayedStream.prototype.release = function() { + this._released = true; + + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; + +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; + +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; } - return (alg); -} + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } -///--- API + this._bufferedEvents.push(args); +}; -module.exports = { +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } - HASH_ALGOS: HASH_ALGOS, - PK_ALGOS: PK_ALGOS, + if (this.dataSize <= this.maxDataSize) { + return; + } - HttpSignatureError: HttpSignatureError, - InvalidAlgorithmError: InvalidAlgorithmError, + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; - validateAlgorithm: validateAlgorithm, - /** - * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. - * - * The intent of this module is to interoperate with OpenSSL only, - * specifically the node crypto module's `verify` method. - * - * @param {String} key an OpenSSH public key. - * @return {String} PEM encoded form of the RSA public key. - * @throws {TypeError} on bad input. - * @throws {Error} on invalid ssh key formatted data. - */ - sshKeyToPEM: function sshKeyToPEM(key) { - assert.string(key, 'ssh_key'); +/***/ }), - var k = sshpk.parseKey(key, 'ssh'); - return (k.toString('pem')); - }, +/***/ 85589: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; - /** - * Generates an OpenSSH fingerprint from an ssh public key. - * - * @param {String} key an OpenSSH public key. - * @return {String} key fingerprint. - * @throws {TypeError} on bad input. - * @throws {Error} if what you passed doesn't look like an ssh public key. - */ - fingerprint: function fingerprint(key) { - assert.string(key, 'ssh_key'); +const legacyErrorCodes = __nccwpck_require__(34370); +const idlUtils = __nccwpck_require__(69497); - var k = sshpk.parseKey(key, 'ssh'); - return (k.fingerprint('md5').toString('hex')); - }, +exports.implementation = class DOMExceptionImpl { + constructor(globalObject, [message, name]) { + this.name = name; + this.message = message; + } - /** - * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa) - * - * The reverse of the above function. - */ - pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) { - assert.equal('string', typeof (pem), 'typeof pem'); + get code() { + return legacyErrorCodes[this.name] || 0; + } +}; - var k = sshpk.parseKey(pem, 'pem'); - k.comment = comment; - return (k.toString('ssh')); +// A proprietary V8 extension that causes the stack property to appear. +exports.init = impl => { + if (Error.captureStackTrace) { + const wrapper = idlUtils.wrapperForImpl(impl); + Error.captureStackTrace(wrapper, wrapper.constructor); } }; /***/ }), -/***/ 51227: +/***/ 37561: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright 2015 Joyent, Inc. - -var assert = __nccwpck_require__(66631); -var crypto = __nccwpck_require__(76417); -var sshpk = __nccwpck_require__(87022); -var utils = __nccwpck_require__(65689); +"use strict"; -var HASH_ALGOS = utils.HASH_ALGOS; -var PK_ALGOS = utils.PK_ALGOS; -var InvalidAlgorithmError = utils.InvalidAlgorithmError; -var HttpSignatureError = utils.HttpSignatureError; -var validateAlgorithm = utils.validateAlgorithm; -///--- Exported API +const conversions = __nccwpck_require__(19463); +const utils = __nccwpck_require__(69497); -module.exports = { - /** - * Verify RSA/DSA signature against public key. You are expected to pass in - * an object that was returned from `parse()`. - * - * @param {Object} parsedSignature the object you got from `parse`. - * @param {String} pubkey RSA/DSA private key PEM. - * @return {Boolean} true if valid, false otherwise. - * @throws {TypeError} if you pass in bad arguments. - * @throws {InvalidAlgorithmError} - */ - verifySignature: function verifySignature(parsedSignature, pubkey) { - assert.object(parsedSignature, 'parsedSignature'); - if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey)) - pubkey = sshpk.parseKey(pubkey); - assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key'); +const impl = utils.implSymbol; +const ctorRegistry = utils.ctorRegistrySymbol; - var alg = validateAlgorithm(parsedSignature.algorithm); - if (alg[0] === 'hmac' || alg[0] !== pubkey.type) - return (false); +const iface = { + // When an interface-module that implements this interface as a mixin is loaded, it will append its own `.is()` + // method into this array. It allows objects that directly implements *those* interfaces to be recognized as + // implementing this mixin interface. + _mixedIntoPredicates: [], + is(obj) { + if (obj) { + if (utils.hasOwn(obj, impl) && obj[impl] instanceof Impl.implementation) { + return true; + } + for (const isMixedInto of module.exports._mixedIntoPredicates) { + if (isMixedInto(obj)) { + return true; + } + } + } + return false; + }, + isImpl(obj) { + if (obj) { + if (obj instanceof Impl.implementation) { + return true; + } - var v = pubkey.createVerify(alg[1]); - v.update(parsedSignature.signingString); - return (v.verify(parsedSignature.params.signature, 'base64')); + const wrapper = utils.wrapperForImpl(obj); + for (const isMixedInto of module.exports._mixedIntoPredicates) { + if (isMixedInto(wrapper)) { + return true; + } + } + } + return false; + }, + convert(obj, { context = "The provided value" } = {}) { + if (module.exports.is(obj)) { + return utils.implForWrapper(obj); + } + throw new TypeError(`${context} is not of type 'DOMException'.`); }, - /** - * Verify HMAC against shared secret. You are expected to pass in an object - * that was returned from `parse()`. - * - * @param {Object} parsedSignature the object you got from `parse`. - * @param {String} secret HMAC shared secret. - * @return {Boolean} true if valid, false otherwise. - * @throws {TypeError} if you pass in bad arguments. - * @throws {InvalidAlgorithmError} - */ - verifyHMAC: function verifyHMAC(parsedSignature, secret) { - assert.object(parsedSignature, 'parsedHMAC'); - assert.string(secret, 'secret'); + create(globalObject, constructorArgs, privateData) { + if (globalObject[ctorRegistry] === undefined) { + throw new Error("Internal error: invalid global object"); + } - var alg = validateAlgorithm(parsedSignature.algorithm); - if (alg[0] !== 'hmac') - return (false); + const ctor = globalObject[ctorRegistry]["DOMException"]; + if (ctor === undefined) { + throw new Error("Internal error: constructor DOMException is not installed on the passed global object"); + } - var hashAlg = alg[1].toUpperCase(); + let obj = Object.create(ctor.prototype); + obj = iface.setup(obj, globalObject, constructorArgs, privateData); + return obj; + }, + createImpl(globalObject, constructorArgs, privateData) { + const obj = iface.create(globalObject, constructorArgs, privateData); + return utils.implForWrapper(obj); + }, + _internalSetup(obj) {}, + setup(obj, globalObject, constructorArgs = [], privateData = {}) { + privateData.wrapper = obj; - var hmac = crypto.createHmac(hashAlg, secret); - hmac.update(parsedSignature.signingString); + iface._internalSetup(obj); + Object.defineProperty(obj, impl, { + value: new Impl.implementation(globalObject, constructorArgs, privateData), + configurable: true + }); - /* - * Now double-hash to avoid leaking timing information - there's - * no easy constant-time compare in JS, so we use this approach - * instead. See for more info: - * https://www.isecpartners.com/blog/2011/february/double-hmac- - * verification.aspx - */ - var h1 = crypto.createHmac(hashAlg, secret); - h1.update(hmac.digest()); - h1 = h1.digest(); - var h2 = crypto.createHmac(hashAlg, secret); - h2.update(new Buffer(parsedSignature.params.signature, 'base64')); - h2 = h2.digest(); + obj[impl][utils.wrapperSymbol] = obj; + if (Impl.init) { + Impl.init(obj[impl], privateData); + } + return obj; + }, - /* Node 0.8 returns strings from .digest(). */ - if (typeof (h1) === 'string') - return (h1 === h2); - /* And node 0.10 lacks the .equals() method on Buffers. */ - if (Buffer.isBuffer(h1) && !h1.equals) - return (h1.toString('binary') === h2.toString('binary')); + install(globalObject) { + class DOMException { + constructor() { + const args = []; + { + let curArg = arguments[0]; + if (curArg !== undefined) { + curArg = conversions["DOMString"](curArg, { context: "Failed to construct 'DOMException': parameter 1" }); + } else { + curArg = ""; + } + args.push(curArg); + } + { + let curArg = arguments[1]; + if (curArg !== undefined) { + curArg = conversions["DOMString"](curArg, { context: "Failed to construct 'DOMException': parameter 2" }); + } else { + curArg = "Error"; + } + args.push(curArg); + } + return iface.setup(Object.create(new.target.prototype), globalObject, args); + } - return (h1.equals(h2)); - } -}; + get name() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return this[impl]["name"]; + } -/***/ }), + get message() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } -/***/ 39695: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return this[impl]["message"]; + } -"use strict"; + get code() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } -var Buffer = __nccwpck_require__(15118).Buffer; + return this[impl]["code"]; + } + } + Object.defineProperties(DOMException.prototype, { + name: { enumerable: true }, + message: { enumerable: true }, + code: { enumerable: true }, + [Symbol.toStringTag]: { value: "DOMException", configurable: true }, + INDEX_SIZE_ERR: { value: 1, enumerable: true }, + DOMSTRING_SIZE_ERR: { value: 2, enumerable: true }, + HIERARCHY_REQUEST_ERR: { value: 3, enumerable: true }, + WRONG_DOCUMENT_ERR: { value: 4, enumerable: true }, + INVALID_CHARACTER_ERR: { value: 5, enumerable: true }, + NO_DATA_ALLOWED_ERR: { value: 6, enumerable: true }, + NO_MODIFICATION_ALLOWED_ERR: { value: 7, enumerable: true }, + NOT_FOUND_ERR: { value: 8, enumerable: true }, + NOT_SUPPORTED_ERR: { value: 9, enumerable: true }, + INUSE_ATTRIBUTE_ERR: { value: 10, enumerable: true }, + INVALID_STATE_ERR: { value: 11, enumerable: true }, + SYNTAX_ERR: { value: 12, enumerable: true }, + INVALID_MODIFICATION_ERR: { value: 13, enumerable: true }, + NAMESPACE_ERR: { value: 14, enumerable: true }, + INVALID_ACCESS_ERR: { value: 15, enumerable: true }, + VALIDATION_ERR: { value: 16, enumerable: true }, + TYPE_MISMATCH_ERR: { value: 17, enumerable: true }, + SECURITY_ERR: { value: 18, enumerable: true }, + NETWORK_ERR: { value: 19, enumerable: true }, + ABORT_ERR: { value: 20, enumerable: true }, + URL_MISMATCH_ERR: { value: 21, enumerable: true }, + QUOTA_EXCEEDED_ERR: { value: 22, enumerable: true }, + TIMEOUT_ERR: { value: 23, enumerable: true }, + INVALID_NODE_TYPE_ERR: { value: 24, enumerable: true }, + DATA_CLONE_ERR: { value: 25, enumerable: true } + }); + Object.defineProperties(DOMException, { + INDEX_SIZE_ERR: { value: 1, enumerable: true }, + DOMSTRING_SIZE_ERR: { value: 2, enumerable: true }, + HIERARCHY_REQUEST_ERR: { value: 3, enumerable: true }, + WRONG_DOCUMENT_ERR: { value: 4, enumerable: true }, + INVALID_CHARACTER_ERR: { value: 5, enumerable: true }, + NO_DATA_ALLOWED_ERR: { value: 6, enumerable: true }, + NO_MODIFICATION_ALLOWED_ERR: { value: 7, enumerable: true }, + NOT_FOUND_ERR: { value: 8, enumerable: true }, + NOT_SUPPORTED_ERR: { value: 9, enumerable: true }, + INUSE_ATTRIBUTE_ERR: { value: 10, enumerable: true }, + INVALID_STATE_ERR: { value: 11, enumerable: true }, + SYNTAX_ERR: { value: 12, enumerable: true }, + INVALID_MODIFICATION_ERR: { value: 13, enumerable: true }, + NAMESPACE_ERR: { value: 14, enumerable: true }, + INVALID_ACCESS_ERR: { value: 15, enumerable: true }, + VALIDATION_ERR: { value: 16, enumerable: true }, + TYPE_MISMATCH_ERR: { value: 17, enumerable: true }, + SECURITY_ERR: { value: 18, enumerable: true }, + NETWORK_ERR: { value: 19, enumerable: true }, + ABORT_ERR: { value: 20, enumerable: true }, + URL_MISMATCH_ERR: { value: 21, enumerable: true }, + QUOTA_EXCEEDED_ERR: { value: 22, enumerable: true }, + TIMEOUT_ERR: { value: 23, enumerable: true }, + INVALID_NODE_TYPE_ERR: { value: 24, enumerable: true }, + DATA_CLONE_ERR: { value: 25, enumerable: true } + }); + if (globalObject[ctorRegistry] === undefined) { + globalObject[ctorRegistry] = Object.create(null); + } + globalObject[ctorRegistry]["DOMException"] = DOMException; -// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. -// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. -// To save memory and loading time, we read table files only when requested. + Object.defineProperty(globalObject, "DOMException", { + configurable: true, + writable: true, + value: DOMException + }); + } +}; // iface +module.exports = iface; -exports._dbcs = DBCSCodec; +const Impl = __nccwpck_require__(85589); -var UNASSIGNED = -1, - GB18030_CODE = -2, - SEQ_START = -10, - NODE_START = -1000, - UNASSIGNED_NODE = new Array(0x100), - DEF_CHAR = -1; -for (var i = 0; i < 0x100; i++) - UNASSIGNED_NODE[i] = UNASSIGNED; +/***/ }), +/***/ 69497: +/***/ ((module, exports) => { -// Class DBCSCodec reads and initializes mapping tables. -function DBCSCodec(codecOptions, iconv) { - this.encodingName = codecOptions.encodingName; - if (!codecOptions) - throw new Error("DBCS codec is called without the data.") - if (!codecOptions.table) - throw new Error("Encoding '" + this.encodingName + "' has no data."); +"use strict"; - // Load tables. - var mappingTable = codecOptions.table(); +// Returns "Type(value) is Object" in ES terminology. +function isObject(value) { + return typeof value === "object" && value !== null || typeof value === "function"; +} - // Decode tables: MBCS -> Unicode. +function hasOwn(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} - // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. - // Trie root is decodeTables[0]. - // Values: >= 0 -> unicode character code. can be > 0xFFFF - // == UNASSIGNED -> unknown/unassigned sequence. - // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. - // <= NODE_START -> index of the next node in our trie to process next byte. - // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. - this.decodeTables = []; - this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. +const wrapperSymbol = Symbol("wrapper"); +const implSymbol = Symbol("impl"); +const sameObjectCaches = Symbol("SameObject caches"); +const ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry"); - // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. - this.decodeTableSeq = []; +function getSameObject(wrapper, prop, creator) { + if (!wrapper[sameObjectCaches]) { + wrapper[sameObjectCaches] = Object.create(null); + } - // Actual mapping tables consist of chunks. Use them to fill up decode tables. - for (var i = 0; i < mappingTable.length; i++) - this._addDecodeChunk(mappingTable[i]); + if (prop in wrapper[sameObjectCaches]) { + return wrapper[sameObjectCaches][prop]; + } - this.defaultCharUnicode = iconv.defaultCharUnicode; + wrapper[sameObjectCaches][prop] = creator(); + return wrapper[sameObjectCaches][prop]; +} - - // Encode tables: Unicode -> DBCS. +function wrapperForImpl(impl) { + return impl ? impl[wrapperSymbol] : null; +} - // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. - // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. - // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). - // == UNASSIGNED -> no conversion found. Output a default char. - // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. - this.encodeTable = []; - - // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of - // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key - // means end of sequence (needed when one sequence is a strict subsequence of another). - // Objects are kept separately from encodeTable to increase performance. - this.encodeTableSeq = []; - - // Some chars can be decoded, but need not be encoded. - var skipEncodeChars = {}; - if (codecOptions.encodeSkipVals) - for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { - var val = codecOptions.encodeSkipVals[i]; - if (typeof val === 'number') - skipEncodeChars[val] = true; - else - for (var j = val.from; j <= val.to; j++) - skipEncodeChars[j] = true; - } - - // Use decode trie to recursively fill out encode tables. - this._fillEncodeTable(0, 0, skipEncodeChars); - - // Add more encoding pairs when needed. - if (codecOptions.encodeAdd) { - for (var uChar in codecOptions.encodeAdd) - if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) - this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); - } - - this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; - if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; - if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); +function implForWrapper(wrapper) { + return wrapper ? wrapper[implSymbol] : null; +} +function tryWrapperForImpl(impl) { + const wrapper = wrapperForImpl(impl); + return wrapper ? wrapper : impl; +} - // Load & create GB18030 tables when needed. - if (typeof codecOptions.gb18030 === 'function') { - this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. +function tryImplForWrapper(wrapper) { + const impl = implForWrapper(wrapper); + return impl ? impl : wrapper; +} - // Add GB18030 decode tables. - var thirdByteNodeIdx = this.decodeTables.length; - var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); +const iterInternalSymbol = Symbol("internal"); +const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); - var fourthByteNodeIdx = this.decodeTables.length; - var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); +function isArrayIndexPropName(P) { + if (typeof P !== "string") { + return false; + } + const i = P >>> 0; + if (i === Math.pow(2, 32) - 1) { + return false; + } + const s = `${i}`; + if (P !== s) { + return false; + } + return true; +} - for (var i = 0x81; i <= 0xFE; i++) { - var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; - var secondByteNode = this.decodeTables[secondByteNodeIdx]; - for (var j = 0x30; j <= 0x39; j++) - secondByteNode[j] = NODE_START - thirdByteNodeIdx; - } - for (var i = 0x81; i <= 0xFE; i++) - thirdByteNode[i] = NODE_START - fourthByteNodeIdx; - for (var i = 0x30; i <= 0x39; i++) - fourthByteNode[i] = GB18030_CODE - } +const byteLengthGetter = + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; +function isArrayBuffer(value) { + try { + byteLengthGetter.call(value); + return true; + } catch (e) { + return false; + } } -DBCSCodec.prototype.encoder = DBCSEncoder; -DBCSCodec.prototype.decoder = DBCSDecoder; +const supportsPropertyIndex = Symbol("supports property index"); +const supportedPropertyIndices = Symbol("supported property indices"); +const supportsPropertyName = Symbol("supports property name"); +const supportedPropertyNames = Symbol("supported property names"); +const indexedGet = Symbol("indexed property get"); +const indexedSetNew = Symbol("indexed property set new"); +const indexedSetExisting = Symbol("indexed property set existing"); +const namedGet = Symbol("named property get"); +const namedSetNew = Symbol("named property set new"); +const namedSetExisting = Symbol("named property set existing"); +const namedDelete = Symbol("named property delete"); -// Decoder helpers -DBCSCodec.prototype._getDecodeTrieNode = function(addr) { - var bytes = []; - for (; addr > 0; addr >>= 8) - bytes.push(addr & 0xFF); - if (bytes.length == 0) - bytes.push(0); +module.exports = exports = { + isObject, + hasOwn, + wrapperSymbol, + implSymbol, + getSameObject, + ctorRegistrySymbol, + wrapperForImpl, + implForWrapper, + tryWrapperForImpl, + tryImplForWrapper, + iterInternalSymbol, + IteratorPrototype, + isArrayBuffer, + isArrayIndexPropName, + supportsPropertyIndex, + supportedPropertyIndices, + supportsPropertyName, + supportedPropertyNames, + indexedGet, + indexedSetNew, + indexedSetExisting, + namedGet, + namedSetNew, + namedSetExisting, + namedDelete +}; - var node = this.decodeTables[0]; - for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. - var val = node[bytes[i]]; - if (val == UNASSIGNED) { // Create new node. - node[bytes[i]] = NODE_START - this.decodeTables.length; - this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); - } - else if (val <= NODE_START) { // Existing node. - node = this.decodeTables[NODE_START - val]; - } - else - throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); - } - return node; -} +/***/ }), +/***/ 19463: +/***/ ((__unused_webpack_module, exports) => { -DBCSCodec.prototype._addDecodeChunk = function(chunk) { - // First element of chunk is the hex mbcs code where we start. - var curAddr = parseInt(chunk[0], 16); +"use strict"; - // Choose the decoding node where we'll write our chars. - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 0xFF; - // Write all other elements of the chunk to the table. - for (var k = 1; k < chunk.length; k++) { - var part = chunk[k]; - if (typeof part === "string") { // String, write as-is. - for (var l = 0; l < part.length;) { - var code = part.charCodeAt(l++); - if (0xD800 <= code && code < 0xDC00) { // Decode surrogate - var codeTrail = part.charCodeAt(l++); - if (0xDC00 <= codeTrail && codeTrail < 0xE000) - writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); - else - throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); - } - else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) - var len = 0xFFF - code + 2; - var seq = []; - for (var m = 0; m < len; m++) - seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. +function _(message, opts) { + return `${opts && opts.context ? opts.context : "Value"} ${message}.`; +} - writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; - this.decodeTableSeq.push(seq); - } - else - writeTable[curAddr++] = code; // Basic char - } - } - else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. - var charCode = writeTable[curAddr - 1] + 1; - for (var l = 0; l < part; l++) - writeTable[curAddr++] = charCode++; - } - else - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); +function type(V) { + if (V === null) { + return "Null"; + } + switch (typeof V) { + case "undefined": + return "Undefined"; + case "boolean": + return "Boolean"; + case "number": + return "Number"; + case "string": + return "String"; + case "symbol": + return "Symbol"; + case "object": + // Falls through + case "function": + // Falls through + default: + // Per ES spec, typeof returns an implemention-defined value that is not any of the existing ones for + // uncallable non-standard exotic objects. Yet Type() which the Web IDL spec depends on returns Object for + // such cases. So treat the default case as an object. + return "Object"; } - if (curAddr > 0xFF) - throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); } -// Encoder helpers -DBCSCodec.prototype._getEncodeBucket = function(uCode) { - var high = uCode >> 8; // This could be > 0xFF because of astral characters. - if (this.encodeTable[high] === undefined) - this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. - return this.encodeTable[high]; -} +// Round x to the nearest integer, choosing the even integer if it lies halfway between two. +function evenRound(x) { + // There are four cases for numbers with fractional part being .5: + // + // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example + // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0 + // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2 + // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0 + // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2 + // (where n is a non-negative integer) + // + // Branch here for cases 1 and 4 + if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) || + (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) { + return censorNegativeZero(Math.floor(x)); + } -DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - if (bucket[low] <= SEQ_START) - this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. - else if (bucket[low] == UNASSIGNED) - bucket[low] = dbcsCode; + return censorNegativeZero(Math.round(x)); } -DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { - - // Get the root of character tree according to first character of the sequence. - var uCode = seq[0]; - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; +function integerPart(n) { + return censorNegativeZero(Math.trunc(n)); +} - var node; - if (bucket[low] <= SEQ_START) { - // There's already a sequence with - use it. - node = this.encodeTableSeq[SEQ_START-bucket[low]]; - } - else { - // There was no sequence object - allocate a new one. - node = {}; - if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. - bucket[low] = SEQ_START - this.encodeTableSeq.length; - this.encodeTableSeq.push(node); - } +function sign(x) { + return x < 0 ? -1 : 1; +} - // Traverse the character tree, allocating new nodes as needed. - for (var j = 1; j < seq.length-1; j++) { - var oldVal = node[uCode]; - if (typeof oldVal === 'object') - node = oldVal; - else { - node = node[uCode] = {} - if (oldVal !== undefined) - node[DEF_CHAR] = oldVal - } +function modulo(x, y) { + // https://tc39.github.io/ecma262/#eqn-modulo + // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos + const signMightNotMatch = x % y; + if (sign(y) !== sign(signMightNotMatch)) { + return signMightNotMatch + y; } + return signMightNotMatch; +} - // Set the leaf to given dbcsCode. - uCode = seq[seq.length-1]; - node[uCode] = dbcsCode; +function censorNegativeZero(x) { + return x === 0 ? 0 : x; } -DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { - var node = this.decodeTables[nodeIdx]; - for (var i = 0; i < 0x100; i++) { - var uCode = node[i]; - var mbCode = prefix + i; - if (skipEncodeChars[mbCode]) - continue; +function createIntegerConversion(bitLength, typeOpts) { + const isSigned = !typeOpts.unsigned; - if (uCode >= 0) - this._setEncodeChar(uCode, mbCode); - else if (uCode <= NODE_START) - this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); - else if (uCode <= SEQ_START) - this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + let lowerBound; + let upperBound; + if (bitLength === 64) { + upperBound = Math.pow(2, 53) - 1; + lowerBound = !isSigned ? 0 : -Math.pow(2, 53) + 1; + } else if (!isSigned) { + lowerBound = 0; + upperBound = Math.pow(2, bitLength) - 1; + } else { + lowerBound = -Math.pow(2, bitLength - 1); + upperBound = Math.pow(2, bitLength - 1) - 1; } -} - + const twoToTheBitLength = Math.pow(2, bitLength); + const twoToOneLessThanTheBitLength = Math.pow(2, bitLength - 1); -// == Encoder ================================================================== + return (V, opts) => { + if (opts === undefined) { + opts = {}; + } -function DBCSEncoder(options, codec) { - // Encoder state - this.leadSurrogate = -1; - this.seqObj = undefined; - - // Static data - this.encodeTable = codec.encodeTable; - this.encodeTableSeq = codec.encodeTableSeq; - this.defaultCharSingleByte = codec.defCharSB; - this.gb18030 = codec.gb18030; -} + let x = +V; + x = censorNegativeZero(x); // Spec discussion ongoing: https://github.com/heycam/webidl/issues/306 -DBCSEncoder.prototype.write = function(str) { - var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), - leadSurrogate = this.leadSurrogate, - seqObj = this.seqObj, nextChar = -1, - i = 0, j = 0; + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw new TypeError(_("is not a finite number", opts)); + } - while (true) { - // 0. Get next character. - if (nextChar === -1) { - if (i == str.length) break; - var uCode = str.charCodeAt(i++); - } - else { - var uCode = nextChar; - nextChar = -1; - } + x = integerPart(x); - // 1. Handle surrogates. - if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. - if (uCode < 0xDC00) { // We've got lead surrogate. - if (leadSurrogate === -1) { - leadSurrogate = uCode; - continue; - } else { - leadSurrogate = uCode; - // Double lead surrogate found. - uCode = UNASSIGNED; - } - } else { // We've got trail surrogate. - if (leadSurrogate !== -1) { - uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); - leadSurrogate = -1; - } else { - // Incomplete surrogate pair - only trail surrogate found. - uCode = UNASSIGNED; - } - + if (x < lowerBound || x > upperBound) { + throw new TypeError(_( + `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts)); } + + return x; } - else if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; + + if (!Number.isNaN(x) && opts.clamp) { + x = Math.min(Math.max(x, lowerBound), upperBound); + x = evenRound(x); + return x; } - // 2. Convert uCode character. - var dbcsCode = UNASSIGNED; - if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence - var resCode = seqObj[uCode]; - if (typeof resCode === 'object') { // Sequence continues. - seqObj = resCode; - continue; + if (!Number.isFinite(x) || x === 0) { + return 0; + } + x = integerPart(x); - } else if (typeof resCode == 'number') { // Sequence finished. Write it. - dbcsCode = resCode; + // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if + // possible. Hopefully it's an optimization for the non-64-bitLength cases too. + if (x >= lowerBound && x <= upperBound) { + return x; + } - } else if (resCode == undefined) { // Current character is not part of the sequence. + // These will not work great for bitLength of 64, but oh well. See the README for more details. + x = modulo(x, twoToTheBitLength); + if (isSigned && x >= twoToOneLessThanTheBitLength) { + return x - twoToTheBitLength; + } + return x; + }; +} - // Try default character for this sequence - resCode = seqObj[DEF_CHAR]; - if (resCode !== undefined) { - dbcsCode = resCode; // Found. Write it. - nextChar = uCode; // Current character will be written too in the next iteration. +exports.any = V => { + return V; +}; - } else { - // TODO: What if we have no default? (resCode == undefined) - // Then, we should write first char of the sequence as-is and try the rest recursively. - // Didn't do it for now because no encoding has this situation yet. - // Currently, just skip the sequence and write current char. - } - } - seqObj = undefined; - } - else if (uCode >= 0) { // Regular character - var subtable = this.encodeTable[uCode >> 8]; - if (subtable !== undefined) - dbcsCode = subtable[uCode & 0xFF]; - - if (dbcsCode <= SEQ_START) { // Sequence start - seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; - continue; - } +exports["void"] = function () { + return undefined; +}; - if (dbcsCode == UNASSIGNED && this.gb18030) { - // Use GB18030 algorithm to find character(s) to write. - var idx = findIdx(this.gb18030.uChars, uCode); - if (idx != -1) { - var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; - newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; - newBuf[j++] = 0x30 + dbcsCode; - continue; - } - } - } +exports.boolean = function (val) { + return !!val; +}; - // 3. Write dbcsCode character. - if (dbcsCode === UNASSIGNED) - dbcsCode = this.defaultCharSingleByte; - - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else if (dbcsCode < 0x10000) { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - else { - newBuf[j++] = dbcsCode >> 16; - newBuf[j++] = (dbcsCode >> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; - } - } +exports.byte = createIntegerConversion(8, { unsigned: false }); +exports.octet = createIntegerConversion(8, { unsigned: true }); - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j); -} +exports.short = createIntegerConversion(16, { unsigned: false }); +exports["unsigned short"] = createIntegerConversion(16, { unsigned: true }); -DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === undefined) - return; // All clean. Most often case. +exports.long = createIntegerConversion(32, { unsigned: false }); +exports["unsigned long"] = createIntegerConversion(32, { unsigned: true }); - var newBuf = Buffer.alloc(10), j = 0; +exports["long long"] = createIntegerConversion(64, { unsigned: false }); +exports["unsigned long long"] = createIntegerConversion(64, { unsigned: true }); - if (this.seqObj) { // We're in the sequence. - var dbcsCode = this.seqObj[DEF_CHAR]; - if (dbcsCode !== undefined) { // Write beginning of the sequence. - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - } else { - // See todo above. - } - this.seqObj = undefined; - } +exports.double = (V, opts) => { + const x = +V; - if (this.leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - newBuf[j++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; + if (!Number.isFinite(x)) { + throw new TypeError(_("is not a finite floating-point value", opts)); } - - return newBuf.slice(0, j); -} -// Export for testing -DBCSEncoder.prototype.findIdx = findIdx; + return x; +}; +exports["unrestricted double"] = V => { + const x = +V; -// == Decoder ================================================================== + return x; +}; -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBuf = Buffer.alloc(0); +exports.float = (V, opts) => { + const x = +V; - // Static data - this.decodeTables = codec.decodeTables; - this.decodeTableSeq = codec.decodeTableSeq; - this.defaultCharUnicode = codec.defaultCharUnicode; - this.gb18030 = codec.gb18030; -} + if (!Number.isFinite(x)) { + throw new TypeError(_("is not a finite floating-point value", opts)); + } -DBCSDecoder.prototype.write = function(buf) { - var newBuf = Buffer.alloc(buf.length*2), - nodeIdx = this.nodeIdx, - prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, - seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. - uCode; + if (Object.is(x, -0)) { + return x; + } - if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. - prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); - - for (var i = 0, j = 0; i < buf.length; i++) { - var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + const y = Math.fround(x); - // Lookup in current trie node. - var uCode = this.decodeTables[nodeIdx][curByte]; + if (!Number.isFinite(y)) { + throw new TypeError(_("is outside the range of a single-precision floating-point value", opts)); + } - if (uCode >= 0) { - // Normal character, just use it. - } - else if (uCode === UNASSIGNED) { // Unknown char. - // TODO: Callback with seq. - //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). - uCode = this.defaultCharUnicode.charCodeAt(0); - } - else if (uCode === GB18030_CODE) { - var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); - var idx = findIdx(this.gb18030.gbChars, ptr); - uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; - } - else if (uCode <= NODE_START) { // Go to next trie node. - nodeIdx = NODE_START - uCode; - continue; - } - else if (uCode <= SEQ_START) { // Output a sequence of chars. - var seq = this.decodeTableSeq[SEQ_START - uCode]; - for (var k = 0; k < seq.length - 1; k++) { - uCode = seq[k]; - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - } - uCode = seq[seq.length-1]; - } - else - throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + return y; +}; - // Write the character to buffer, handling higher planes using surrogate pair. - if (uCode > 0xFFFF) { - uCode -= 0x10000; - var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); - newBuf[j++] = uCodeLead & 0xFF; - newBuf[j++] = uCodeLead >> 8; +exports["unrestricted float"] = V => { + const x = +V; - uCode = 0xDC00 + uCode % 0x400; - } - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; + if (isNaN(x)) { + return x; + } - // Reset trie node. - nodeIdx = 0; seqStart = i+1; + if (Object.is(x, -0)) { + return x; } - this.nodeIdx = nodeIdx; - this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); - return newBuf.slice(0, j).toString('ucs2'); -} + return Math.fround(x); +}; -DBCSDecoder.prototype.end = function() { - var ret = ''; +exports.DOMString = function (V, opts) { + if (opts === undefined) { + opts = {}; + } - // Try to parse all remaining chars. - while (this.prevBuf.length > 0) { - // Skip 1 character in the buffer. - ret += this.defaultCharUnicode; - var buf = this.prevBuf.slice(1); + if (opts.treatNullAsEmptyString && V === null) { + return ""; + } - // Parse remaining as usual. - this.prevBuf = Buffer.alloc(0); - this.nodeIdx = 0; - if (buf.length > 0) - ret += this.write(buf); + if (typeof V === "symbol") { + throw new TypeError(_("is a symbol, which cannot be converted to a string", opts)); } - this.nodeIdx = 0; - return ret; -} + return String(V); +}; -// Binary search for GB18030. Returns largest i such that table[i] <= val. -function findIdx(table, val) { - if (table[0] > val) - return -1; +exports.ByteString = (V, opts) => { + const x = exports.DOMString(V, opts); + let c; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw new TypeError(_("is not a valid ByteString", opts)); + } + } - var l = 0, r = table.length; - while (l < r-1) { // always table[l] <= val < table[r] - var mid = l + Math.floor((r-l+1)/2); - if (table[mid] <= val) - l = mid; - else - r = mid; + return x; +}; + +exports.USVString = (V, opts) => { + const S = exports.DOMString(V, opts); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } } - return l; -} + return U.join(""); +}; +exports.object = (V, opts) => { + if (type(V) !== "Object") { + throw new TypeError(_("is not an object", opts)); + } -/***/ }), + return V; +}; -/***/ 91386: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Not exported, but used in Function and VoidFunction. -"use strict"; +// Neither Function nor VoidFunction is defined with [TreatNonObjectAsNull], so +// handling for that is omitted. +function convertCallbackFunction(V, opts) { + if (typeof V !== "function") { + throw new TypeError(_("is not a function", opts)); + } + return V; +} +const abByteLengthGetter = + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; -// Description of supported double byte encodings and aliases. -// Tables are not require()-d until they are needed to speed up library load. -// require()-s are direct to support Browserify. +function isArrayBuffer(V) { + try { + abByteLengthGetter.call(V); + return true; + } catch (e) { + return false; + } +} -module.exports = { - - // == Japanese/ShiftJIS ==================================================== - // All japanese encodings are based on JIS X set of standards: - // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. - // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. - // Has several variations in 1978, 1983, 1990 and 1997. - // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. - // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. - // 2 planes, first is superset of 0208, second - revised 0212. - // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) +// I don't think we can reliably detect detached ArrayBuffers. +exports.ArrayBuffer = (V, opts) => { + if (!isArrayBuffer(V)) { + throw new TypeError(_("is not a view on an ArrayBuffer object", opts)); + } + return V; +}; - // Byte encodings are: - // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte - // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. - // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. - // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. - // 0x00-0x7F - lower part of 0201 - // 0x8E, 0xA1-0xDF - upper part of 0201 - // (0xA1-0xFE)x2 - 0208 plane (94x94). - // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). - // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. - // Used as-is in ISO2022 family. - // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, - // 0201-1976 Roman, 0208-1978, 0208-1983. - // * ISO2022-JP-1: Adds esc seq for 0212-1990. - // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. - // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. - // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. - // - // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. - // - // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html +const dvByteLengthGetter = + Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get; +exports.DataView = (V, opts) => { + try { + dvByteLengthGetter.call(V); + return V; + } catch (e) { + throw new TypeError(_("is not a view on an DataView object", opts)); + } +}; - 'shiftjis': { - type: '_dbcs', - table: function() { return __nccwpck_require__(64108) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - encodeSkipVals: [{from: 0xED40, to: 0xF940}], - }, - 'csshiftjis': 'shiftjis', - 'mskanji': 'shiftjis', - 'sjis': 'shiftjis', - 'windows31j': 'shiftjis', - 'ms31j': 'shiftjis', - 'xsjis': 'shiftjis', - 'windows932': 'shiftjis', - 'ms932': 'shiftjis', - '932': 'shiftjis', - 'cp932': 'shiftjis', +[ + Int8Array, Int16Array, Int32Array, Uint8Array, + Uint16Array, Uint32Array, Uint8ClampedArray, Float32Array, Float64Array +].forEach(func => { + const name = func.name; + const article = /^[AEIOU]/.test(name) ? "an" : "a"; + exports[name] = (V, opts) => { + if (!ArrayBuffer.isView(V) || V.constructor.name !== name) { + throw new TypeError(_(`is not ${article} ${name} object`, opts)); + } - 'eucjp': { - type: '_dbcs', - table: function() { return __nccwpck_require__(72417) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - }, + return V; + }; +}); - // TODO: KDDI extension to Shift_JIS - // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. - // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. +// Common definitions +exports.ArrayBufferView = (V, opts) => { + if (!ArrayBuffer.isView(V)) { + throw new TypeError(_("is not a view on an ArrayBuffer object", opts)); + } - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + return V; +}; - // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 - 'gb2312': 'cp936', - 'gb231280': 'cp936', - 'gb23121980': 'cp936', - 'csgb2312': 'cp936', - 'csiso58gb231280': 'cp936', - 'euccn': 'cp936', +exports.BufferSource = (V, opts) => { + if (!ArrayBuffer.isView(V) && !isArrayBuffer(V)) { + throw new TypeError(_("is not an ArrayBuffer object or a view on one", opts)); + } - // Microsoft's CP936 is a subset and approximation of GBK. - 'windows936': 'cp936', - 'ms936': 'cp936', - '936': 'cp936', - 'cp936': { - type: '_dbcs', - table: function() { return __nccwpck_require__(97803) }, - }, + return V; +}; - // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. - 'gbk': { - type: '_dbcs', - table: function() { return __nccwpck_require__(97803).concat(__nccwpck_require__(37419)) }, - }, - 'xgbk': 'gbk', - 'isoir58': 'gbk', +exports.DOMTimeStamp = exports["unsigned long long"]; - // GB18030 is an algorithmic extension of GBK. - // Main source: https://www.w3.org/TR/encoding/#gbk-encoder - // http://icu-project.org/docs/papers/gb18030.html - // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml - // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 - 'gb18030': { - type: '_dbcs', - table: function() { return __nccwpck_require__(97803).concat(__nccwpck_require__(37419)) }, - gb18030: function() { return __nccwpck_require__(86351) }, - encodeSkipVals: [0x80], - encodeAdd: {'€': 0xA2E3}, - }, +exports.Function = convertCallbackFunction; - 'chinese': 'gb18030', +exports.VoidFunction = convertCallbackFunction; - // == Korean =============================================================== - // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. - 'windows949': 'cp949', - 'ms949': 'cp949', - '949': 'cp949', - 'cp949': { - type: '_dbcs', - table: function() { return __nccwpck_require__(87013) }, - }, +/***/ }), - 'cseuckr': 'cp949', - 'csksc56011987': 'cp949', - 'euckr': 'cp949', - 'isoir149': 'cp949', - 'korean': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'ksc5601': 'cp949', +/***/ 57617: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; - // == Big5/Taiwan/Hong Kong ================================================ - // There are lots of tables for Big5 and cp950. Please see the following links for history: - // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html - // Variations, in roughly number of defined chars: - // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT - // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ - // * Big5-2003 (Taiwan standard) almost superset of cp950. - // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. - // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. - // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. - // Plus, it has 4 combining sequences. - // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 - // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. - // Implementations are not consistent within browsers; sometimes labeled as just big5. - // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. - // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 - // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. - // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt - // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt - // - // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder - // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. +const DOMException = __nccwpck_require__(37561); - 'windows950': 'cp950', - 'ms950': 'cp950', - '950': 'cp950', - 'cp950': { - type: '_dbcs', - table: function() { return __nccwpck_require__(33104) }, - }, +// Special install function to make the DOMException inherit from Error. +// https://heycam.github.io/webidl/#es-DOMException-specialness +function installOverride(globalObject) { + if (typeof globalObject.Error !== "function") { + throw new Error("Internal error: Error constructor is not present on the given global object."); + } - // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. - 'big5': 'big5hkscs', - 'big5hkscs': { - type: '_dbcs', - table: function() { return __nccwpck_require__(33104).concat(__nccwpck_require__(43612)) }, - encodeSkipVals: [0xa2cc], - }, + DOMException.install(globalObject); + Object.setPrototypeOf(globalObject.DOMException.prototype, globalObject.Error.prototype); +} - 'cnbig5': 'big5hkscs', - 'csbig5': 'big5hkscs', - 'xxbig5': 'big5hkscs', -}; +module.exports = {...DOMException, install: installOverride }; /***/ }), -/***/ 82733: +/***/ 49865: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +var crypto = __nccwpck_require__(6113); +var BigInteger = (__nccwpck_require__(85587).BigInteger); +var ECPointFp = (__nccwpck_require__(3943).ECPointFp); +var Buffer = (__nccwpck_require__(15118).Buffer); +exports.ECCurves = __nccwpck_require__(41452); +// zero prepad +function unstupid(hex,len) +{ + return (hex.length >= len) ? hex : unstupid("0"+hex,len); +} -// Update this array if you add/rename/remove files in this directory. -// We support Browserify by skipping automatic module discovery and requiring modules directly. -var modules = [ - __nccwpck_require__(12376), - __nccwpck_require__(11155), - __nccwpck_require__(51644), - __nccwpck_require__(26657), - __nccwpck_require__(41080), - __nccwpck_require__(21012), - __nccwpck_require__(39695), - __nccwpck_require__(91386), -]; +exports.ECKey = function(curve, key, isPublic) +{ + var priv; + var c = curve(); + var n = c.getN(); + var bytes = Math.floor(n.bitLength()/8); -// Put all encoding/alias/codec definitions to single object and export it. -for (var i = 0; i < modules.length; i++) { - var module = modules[i]; - for (var enc in module) - if (Object.prototype.hasOwnProperty.call(module, enc)) - exports[enc] = module[enc]; + if(key) + { + if(isPublic) + { + var curve = c.getCurve(); +// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format +// var y = key.slice(bytes+1); +// this.P = new ECPointFp(curve, +// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)), +// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16))); + this.P = curve.decodePointHex(key.toString("hex")); + }else{ + if(key.length != bytes) return false; + priv = new BigInteger(key.toString("hex"), 16); + } + }else{ + var n1 = n.subtract(BigInteger.ONE); + var r = new BigInteger(crypto.randomBytes(n.bitLength())); + priv = r.mod(n1).add(BigInteger.ONE); + this.P = c.getG().multiply(priv); + } + if(this.P) + { +// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2); +// this.PublicKey = Buffer.from("04"+pubhex,"hex"); + this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex"); + } + if(priv) + { + this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex"); + this.deriveSharedSecret = function(key) + { + if(!key || !key.P) return false; + var S = key.P.multiply(priv); + return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); + } + } } + /***/ }), -/***/ 12376: +/***/ 3943: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - -var Buffer = __nccwpck_require__(15118).Buffer; +// Basic Javascript Elliptic Curve implementation +// Ported loosely from BouncyCastle's Java EC code +// Only Fp curves implemented for now -// Export Node.js internal encodings. +// Requires jsbn.js and jsbn2.js +var BigInteger = (__nccwpck_require__(85587).BigInteger) +var Barrett = BigInteger.prototype.Barrett -module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true}, - cesu8: { type: "_internal", bomAware: true}, - unicode11utf8: "utf8", +// ---------------- +// ECFieldElementFp - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", +// constructor +function ECFieldElementFp(q,x) { + this.x = x; + // TODO if(x.compareTo(q) >= 0) error + this.q = q; +} - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, +function feFpEquals(other) { + if(other == this) return true; + return (this.q.equals(other.q) && this.x.equals(other.x)); +} - // Codec. - _internal: InternalCodec, -}; +function feFpToBigInteger() { + return this.x; +} -//------------------------------------------------------------------------------ +function feFpNegate() { + return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); +} -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; +function feFpAdd(b) { + return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); +} - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; +function feFpSubtract(b) { + return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); +} - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; - } +function feFpMultiply(b) { + return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); +} + +function feFpSquare() { + return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); +} + +function feFpDivide(b) { + return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); +} + +ECFieldElementFp.prototype.equals = feFpEquals; +ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; +ECFieldElementFp.prototype.negate = feFpNegate; +ECFieldElementFp.prototype.add = feFpAdd; +ECFieldElementFp.prototype.subtract = feFpSubtract; +ECFieldElementFp.prototype.multiply = feFpMultiply; +ECFieldElementFp.prototype.square = feFpSquare; +ECFieldElementFp.prototype.divide = feFpDivide; + +// ---------------- +// ECPointFp + +// constructor +function ECPointFp(curve,x,y,z) { + this.curve = curve; + this.x = x; + this.y = y; + // Projective coordinates: either zinv == null or z * zinv == 1 + // z and zinv are just BigIntegers, not fieldElements + if(z == null) { + this.z = BigInteger.ONE; + } + else { + this.z = z; } + this.zinv = null; + //TODO: compression flag } -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; +function pointFpGetX() { + if(this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.x.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); +} -//------------------------------------------------------------------------------ +function pointFpGetY() { + if(this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.y.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); +} -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = __nccwpck_require__(24304).StringDecoder; +function pointFpEquals(other) { + if(other == this) return true; + if(this.isInfinity()) return other.isInfinity(); + if(other.isInfinity()) return this.isInfinity(); + var u, v; + // u = Y2 * Z1 - Y1 * Z2 + u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); + if(!u.equals(BigInteger.ZERO)) return false; + // v = X2 * Z1 - X1 * Z2 + v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); + return v.equals(BigInteger.ZERO); +} -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; +function pointFpIsInfinity() { + if((this.x == null) && (this.y == null)) return true; + return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); +} +function pointFpNegate() { + return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); +} -function InternalDecoder(options, codec) { - StringDecoder.call(this, codec.enc); +function pointFpAdd(b) { + if(this.isInfinity()) return b; + if(b.isInfinity()) return this; + + // u = Y2 * Z1 - Y1 * Z2 + var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); + // v = X2 * Z1 - X1 * Z2 + var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); + + if(BigInteger.ZERO.equals(v)) { + if(BigInteger.ZERO.equals(u)) { + return this.twice(); // this == b, so double + } + return this.curve.getInfinity(); // this = -b, so infinity + } + + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); + var x2 = b.x.toBigInteger(); + var y2 = b.y.toBigInteger(); + + var v2 = v.square(); + var v3 = v2.multiply(v); + var x1v2 = x1.multiply(v2); + var zu2 = u.square().multiply(this.z); + + // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) + var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); + // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 + var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); + // z3 = v^3 * z1 * z2 + var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); + + return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); } -InternalDecoder.prototype = StringDecoder.prototype; +function pointFpTwice() { + if(this.isInfinity()) return this; + if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); + // TODO: optimized handling of constants + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); -//------------------------------------------------------------------------------ -// Encoder is mostly trivial + var y1z1 = y1.multiply(this.z); + var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); + var a = this.curve.a.toBigInteger(); -function InternalEncoder(options, codec) { - this.enc = codec.enc; + // w = 3 * x1^2 + a * z1^2 + var w = x1.square().multiply(THREE); + if(!BigInteger.ZERO.equals(a)) { + w = w.add(this.z.square().multiply(a)); + } + w = w.mod(this.curve.q); + //this.curve.reduce(w); + // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) + var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); + // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 + var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); + // z3 = 8 * (y1 * z1)^3 + var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); + + return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); } -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); +// Simple NAF (Non-Adjacent Form) multiplication algorithm +// TODO: modularize the multiplication algorithm +function pointFpMultiply(k) { + if(this.isInfinity()) return this; + if(k.signum() == 0) return this.curve.getInfinity(); + + var e = k; + var h = e.multiply(new BigInteger("3")); + + var neg = this.negate(); + var R = this; + + var i; + for(i = h.bitLength() - 2; i > 0; --i) { + R = R.twice(); + + var hBit = h.testBit(i); + var eBit = e.testBit(i); + + if (hBit != eBit) { + R = R.add(hBit ? this : neg); + } + } + + return R; } -InternalEncoder.prototype.end = function() { +// Compute this*j + x*k (simultaneous multiplication) +function pointFpMultiplyTwo(j,x,k) { + var i; + if(j.bitLength() > k.bitLength()) + i = j.bitLength() - 1; + else + i = k.bitLength() - 1; + + var R = this.curve.getInfinity(); + var both = this.add(x); + while(i >= 0) { + R = R.twice(); + if(j.testBit(i)) { + if(k.testBit(i)) { + R = R.add(both); + } + else { + R = R.add(this); + } + } + else { + if(k.testBit(i)) { + R = R.add(x); + } + } + --i; + } + + return R; } +ECPointFp.prototype.getX = pointFpGetX; +ECPointFp.prototype.getY = pointFpGetY; +ECPointFp.prototype.equals = pointFpEquals; +ECPointFp.prototype.isInfinity = pointFpIsInfinity; +ECPointFp.prototype.negate = pointFpNegate; +ECPointFp.prototype.add = pointFpAdd; +ECPointFp.prototype.twice = pointFpTwice; +ECPointFp.prototype.multiply = pointFpMultiply; +ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; -//------------------------------------------------------------------------------ -// Except base64 encoder, which must keep its state. +// ---------------- +// ECCurveFp -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; +// constructor +function ECCurveFp(q,a,b) { + this.q = q; + this.a = this.fromBigInteger(a); + this.b = this.fromBigInteger(b); + this.infinity = new ECPointFp(this, null, null); + this.reducer = new Barrett(this.q); } -InternalEncoderBase64.prototype.write = function(str) { - str = this.prevStr + str; - var completeQuads = str.length - (str.length % 4); - this.prevStr = str.slice(completeQuads); - str = str.slice(0, completeQuads); +function curveFpGetQ() { + return this.q; +} - return Buffer.from(str, "base64"); +function curveFpGetA() { + return this.a; } -InternalEncoderBase64.prototype.end = function() { - return Buffer.from(this.prevStr, "base64"); +function curveFpGetB() { + return this.b; } +function curveFpEquals(other) { + if(other == this) return true; + return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); +} -//------------------------------------------------------------------------------ -// CESU-8 encoder is also special. +function curveFpGetInfinity() { + return this.infinity; +} -function InternalEncoderCesu8(options, codec) { +function curveFpFromBigInteger(x) { + return new ECFieldElementFp(this.q, x); } -InternalEncoderCesu8.prototype.write = function(str) { - var buf = Buffer.alloc(str.length * 3), bufIdx = 0; - for (var i = 0; i < str.length; i++) { - var charCode = str.charCodeAt(i); - // Naive implementation, but it works because CESU-8 is especially easy - // to convert from UTF-16 (which all JS strings are encoded in). - if (charCode < 0x80) - buf[bufIdx++] = charCode; - else if (charCode < 0x800) { - buf[bufIdx++] = 0xC0 + (charCode >>> 6); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - else { // charCode will always be < 0x10000 in javascript. - buf[bufIdx++] = 0xE0 + (charCode >>> 12); - buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } +function curveReduce(x) { + this.reducer.reduce(x); +} + +// for now, work with hex strings because they're easier in JS +function curveFpDecodePointHex(s) { + switch(parseInt(s.substr(0,2), 16)) { // first byte + case 0: + return this.infinity; + case 2: + case 3: + // point compression not supported yet + return null; + case 4: + case 6: + case 7: + var len = (s.length - 2) / 2; + var xHex = s.substr(2, len); + var yHex = s.substr(len+2, len); + + return new ECPointFp(this, + this.fromBigInteger(new BigInteger(xHex, 16)), + this.fromBigInteger(new BigInteger(yHex, 16))); + + default: // unsupported + return null; } - return buf.slice(0, bufIdx); } -InternalEncoderCesu8.prototype.end = function() { +function curveFpEncodePointHex(p) { + if (p.isInfinity()) return "00"; + var xHex = p.getX().toBigInteger().toString(16); + var yHex = p.getY().toBigInteger().toString(16); + var oLen = this.getQ().toString(16).length; + if ((oLen % 2) != 0) oLen++; + while (xHex.length < oLen) { + xHex = "0" + xHex; + } + while (yHex.length < oLen) { + yHex = "0" + yHex; + } + return "04" + xHex + yHex; } -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ +ECCurveFp.prototype.getQ = curveFpGetQ; +ECCurveFp.prototype.getA = curveFpGetA; +ECCurveFp.prototype.getB = curveFpGetB; +ECCurveFp.prototype.equals = curveFpEquals; +ECCurveFp.prototype.getInfinity = curveFpGetInfinity; +ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; +ECCurveFp.prototype.reduce = curveReduce; +//ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; +ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; -function InternalDecoderCesu8(options, codec) { - this.acc = 0; - this.contBytes = 0; - this.accBytes = 0; - this.defaultCharUnicode = codec.defaultCharUnicode; +// from: https://github.com/kaielvin/jsbn-ec-point-compression +ECCurveFp.prototype.decodePointHex = function(s) +{ + var yIsEven; + switch(parseInt(s.substr(0,2), 16)) { // first byte + case 0: + return this.infinity; + case 2: + yIsEven = false; + case 3: + if(yIsEven == undefined) yIsEven = true; + var len = s.length - 2; + var xHex = s.substr(2, len); + var x = this.fromBigInteger(new BigInteger(xHex,16)); + var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); + var beta = alpha.sqrt(); + + if (beta == null) throw "Invalid point compression"; + + var betaValue = beta.toBigInteger(); + if (betaValue.testBit(0) != yIsEven) + { + // Use the other root + beta = this.fromBigInteger(this.getQ().subtract(betaValue)); + } + return new ECPointFp(this,x,beta); + case 4: + case 6: + case 7: + var len = (s.length - 2) / 2; + var xHex = s.substr(2, len); + var yHex = s.substr(len+2, len); + + return new ECPointFp(this, + this.fromBigInteger(new BigInteger(xHex, 16)), + this.fromBigInteger(new BigInteger(yHex, 16))); + + default: // unsupported + return null; + } } +ECCurveFp.prototype.encodeCompressedPointHex = function(p) +{ + if (p.isInfinity()) return "00"; + var xHex = p.getX().toBigInteger().toString(16); + var oLen = this.getQ().toString(16).length; + if ((oLen % 2) != 0) oLen++; + while (xHex.length < oLen) + xHex = "0" + xHex; + var yPrefix; + if(p.getY().toBigInteger().isEven()) yPrefix = "02"; + else yPrefix = "03"; -InternalDecoderCesu8.prototype.write = function(buf) { - var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, - res = ''; - for (var i = 0; i < buf.length; i++) { - var curByte = buf[i]; - if ((curByte & 0xC0) !== 0x80) { // Leading byte - if (contBytes > 0) { // Previous code is invalid - res += this.defaultCharUnicode; - contBytes = 0; - } + return yPrefix + xHex; +} - if (curByte < 0x80) { // Single-byte code - res += String.fromCharCode(curByte); - } else if (curByte < 0xE0) { // Two-byte code - acc = curByte & 0x1F; - contBytes = 1; accBytes = 1; - } else if (curByte < 0xF0) { // Three-byte code - acc = curByte & 0x0F; - contBytes = 2; accBytes = 1; - } else { // Four or more are not supported for CESU-8. - res += this.defaultCharUnicode; + +ECFieldElementFp.prototype.getR = function() +{ + if(this.r != undefined) return this.r; + + this.r = null; + var bitLength = this.q.bitLength(); + if (bitLength > 128) + { + var firstWord = this.q.shiftRight(bitLength - 64); + if (firstWord.intValue() == -1) + { + this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); + } + } + return this.r; +} +ECFieldElementFp.prototype.modMult = function(x1,x2) +{ + return this.modReduce(x1.multiply(x2)); +} +ECFieldElementFp.prototype.modReduce = function(x) +{ + if (this.getR() != null) + { + var qLen = q.bitLength(); + while (x.bitLength() > (qLen + 1)) + { + var u = x.shiftRight(qLen); + var v = x.subtract(u.shiftLeft(qLen)); + if (!this.getR().equals(BigInteger.ONE)) + { + u = u.multiply(this.getR()); } - } else { // Continuation byte - if (contBytes > 0) { // We're waiting for it. - acc = (acc << 6) | (curByte & 0x3f); - contBytes--; accBytes++; - if (contBytes === 0) { - // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) - if (accBytes === 2 && acc < 0x80 && acc > 0) - res += this.defaultCharUnicode; - else if (accBytes === 3 && acc < 0x800) - res += this.defaultCharUnicode; - else - // Actually add character. - res += String.fromCharCode(acc); - } - } else { // Unexpected continuation byte - res += this.defaultCharUnicode; + x = u.add(v); + } + while (x.compareTo(q) >= 0) + { + x = x.subtract(q); + } + } + else + { + x = x.mod(q); + } + return x; +} +ECFieldElementFp.prototype.sqrt = function() +{ + if (!this.q.testBit(0)) throw "unsupported"; + + // p mod 4 == 3 + if (this.q.testBit(1)) + { + var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); + return z.square().equals(this) ? z : null; + } + + // p mod 4 == 1 + var qMinusOne = this.q.subtract(BigInteger.ONE); + + var legendreExponent = qMinusOne.shiftRight(1); + if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) + { + return null; + } + + var u = qMinusOne.shiftRight(2); + var k = u.shiftLeft(1).add(BigInteger.ONE); + + var Q = this.x; + var fourQ = modDouble(modDouble(Q)); + + var U, V; + do + { + var P; + do + { + P = new BigInteger(this.q.bitLength(), new SecureRandom()); + } + while (P.compareTo(this.q) >= 0 + || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); + + var result = this.lucasSequence(P, Q, k); + U = result[0]; + V = result[1]; + + if (this.modMult(V, V).equals(fourQ)) + { + // Integer division by 2, mod q + if (V.testBit(0)) + { + V = V.add(q); } + + V = V.shiftRight(1); + + return new ECFieldElementFp(q,V); } } - this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; - return res; + while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); + + return null; } +ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) +{ + var n = k.bitLength(); + var s = k.getLowestSetBit(); -InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) - res += this.defaultCharUnicode; - return res; + var Uh = BigInteger.ONE; + var Vl = BigInteger.TWO; + var Vh = P; + var Ql = BigInteger.ONE; + var Qh = BigInteger.ONE; + + for (var j = n - 1; j >= s + 1; --j) + { + Ql = this.modMult(Ql, Qh); + + if (k.testBit(j)) + { + Qh = this.modMult(Ql, Q); + Uh = this.modMult(Uh, Vh); + Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); + } + else + { + Qh = Ql; + Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); + Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); + } + } + + Ql = this.modMult(Ql, Qh); + Qh = this.modMult(Ql, Q); + Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); + Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Ql = this.modMult(Ql, Qh); + + for (var j = 1; j <= s; ++j) + { + Uh = this.modMult(Uh, Vl); + Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); + Ql = this.modMult(Ql, Ql); + } + + return [ Uh, Vl ]; +} + +var exports = { + ECCurveFp: ECCurveFp, + ECPointFp: ECPointFp, + ECFieldElementFp: ECFieldElementFp } +module.exports = exports + /***/ }), -/***/ 26657: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 41452: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +// Named EC curves -var Buffer = __nccwpck_require__(15118).Buffer; +// Requires ec.js, jsbn.js, and jsbn2.js +var BigInteger = (__nccwpck_require__(85587).BigInteger) +var ECCurveFp = (__nccwpck_require__(3943).ECCurveFp) -// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that -// correspond to encoded bytes (if 128 - then lower half is ASCII). -exports._sbcs = SBCSCodec; -function SBCSCodec(codecOptions, iconv) { - if (!codecOptions) - throw new Error("SBCS codec is called without the data.") - - // Prepare char buffer for decoding. - if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) - throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); - - if (codecOptions.chars.length === 128) { - var asciiString = ""; - for (var i = 0; i < 128; i++) - asciiString += String.fromCharCode(i); - codecOptions.chars = asciiString + codecOptions.chars; - } +// ---------------- +// X9ECParameters - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); +// constructor +function X9ECParameters(curve,g,n,h) { + this.curve = curve; + this.g = g; + this.n = n; + this.h = h; +} - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; +function x9getCurve() { + return this.curve; +} - this.encodeBuf = encodeBuf; +function x9getG() { + return this.g; } -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; +function x9getN() { + return this.n; +} + +function x9getH() { + return this.h; +} +X9ECParameters.prototype.getCurve = x9getCurve; +X9ECParameters.prototype.getG = x9getG; +X9ECParameters.prototype.getN = x9getN; +X9ECParameters.prototype.getH = x9getH; -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; +// ---------------- +// SECNamedCurves + +function fromHex(s) { return new BigInteger(s, 16); } + +function secp128r1() { + // p = 2^128 - 2^97 - 1 + var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); + var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); + //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); + var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "161FF7528B899B2D0C28607CA52C5B86" + + "CF5AC8395BAFEB13C02DA292DDED7A83"); + return new X9ECParameters(curve, G, n, h); } -SBCSEncoder.prototype.write = function(str) { - var buf = Buffer.alloc(str.length); - for (var i = 0; i < str.length; i++) - buf[i] = this.encodeBuf[str.charCodeAt(i)]; - - return buf; +function secp160k1() { + // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); + var a = BigInteger.ZERO; + var b = fromHex("7"); + //byte[] S = null; + var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" + + "938CF935318FDCED6BC28286531733C3F03C4FEE"); + return new X9ECParameters(curve, G, n, h); } -SBCSEncoder.prototype.end = function() { +function secp160r1() { + // p = 2^160 - 2^31 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); + var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); + //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); + var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "4A96B5688EF573284664698968C38BB913CBFC82" + + "23A628553168947D59DCC912042351377AC5FB32"); + return new X9ECParameters(curve, G, n, h); } +function secp192k1() { + // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); + var a = BigInteger.ZERO; + var b = fromHex("3"); + //byte[] S = null; + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" + + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); + return new X9ECParameters(curve, G, n, h); +} -function SBCSDecoder(options, codec) { - this.decodeBuf = codec.decodeBuf; +function secp192r1() { + // p = 2^192 - 2^64 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); + var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); + //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" + + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); + return new X9ECParameters(curve, G, n, h); } -SBCSDecoder.prototype.write = function(buf) { - // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. - var decodeBuf = this.decodeBuf; - var newBuf = Buffer.alloc(buf.length*2); - var idx1 = 0, idx2 = 0; - for (var i = 0; i < buf.length; i++) { - idx1 = buf[i]*2; idx2 = i*2; - newBuf[idx2] = decodeBuf[idx1]; - newBuf[idx2+1] = decodeBuf[idx1+1]; - } - return newBuf.toString('ucs2'); +function secp224r1() { + // p = 2^224 - 2^96 + 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); + var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); + //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" + + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); + return new X9ECParameters(curve, G, n, h); } -SBCSDecoder.prototype.end = function() { +function secp256r1() { + // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 + var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); + var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); + //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); + var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" + + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); + return new X9ECParameters(curve, G, n, h); +} + +// TODO: make this into a proper hashtable +function getSECCurveByName(name) { + if(name == "secp128r1") return secp128r1(); + if(name == "secp160k1") return secp160k1(); + if(name == "secp160r1") return secp160r1(); + if(name == "secp192k1") return secp192k1(); + if(name == "secp192r1") return secp192r1(); + if(name == "secp224r1") return secp224r1(); + if(name == "secp256r1") return secp256r1(); + return null; +} + +module.exports = { + "secp128r1":secp128r1, + "secp160k1":secp160k1, + "secp160r1":secp160r1, + "secp192k1":secp192k1, + "secp192r1":secp192r1, + "secp224r1":secp224r1, + "secp256r1":secp256r1 } /***/ }), -/***/ 21012: +/***/ 38171: /***/ ((module) => { "use strict"; -// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. -module.exports = { - "437": "cp437", - "737": "cp737", - "775": "cp775", - "850": "cp850", - "852": "cp852", - "855": "cp855", - "856": "cp856", - "857": "cp857", - "858": "cp858", - "860": "cp860", - "861": "cp861", - "862": "cp862", - "863": "cp863", - "864": "cp864", - "865": "cp865", - "866": "cp866", - "869": "cp869", - "874": "windows874", - "922": "cp922", - "1046": "cp1046", - "1124": "cp1124", - "1125": "cp1125", - "1129": "cp1129", - "1133": "cp1133", - "1161": "cp1161", - "1162": "cp1162", - "1163": "cp1163", - "1250": "windows1250", - "1251": "windows1251", - "1252": "windows1252", - "1253": "windows1253", - "1254": "windows1254", - "1255": "windows1255", - "1256": "windows1256", - "1257": "windows1257", - "1258": "windows1258", - "28591": "iso88591", - "28592": "iso88592", - "28593": "iso88593", - "28594": "iso88594", - "28595": "iso88595", - "28596": "iso88596", - "28597": "iso88597", - "28598": "iso88598", - "28599": "iso88599", - "28600": "iso885910", - "28601": "iso885911", - "28603": "iso885913", - "28604": "iso885914", - "28605": "iso885915", - "28606": "iso885916", - "windows874": { - "type": "_sbcs", - "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "win874": "windows874", - "cp874": "windows874", - "windows1250": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "win1250": "windows1250", - "cp1250": "windows1250", - "windows1251": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "win1251": "windows1251", - "cp1251": "windows1251", - "windows1252": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "win1252": "windows1252", - "cp1252": "windows1252", - "windows1253": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "win1253": "windows1253", - "cp1253": "windows1253", - "windows1254": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "win1254": "windows1254", - "cp1254": "windows1254", - "windows1255": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "win1255": "windows1255", - "cp1255": "windows1255", - "windows1256": { - "type": "_sbcs", - "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" - }, - "win1256": "windows1256", - "cp1256": "windows1256", - "windows1257": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" - }, - "win1257": "windows1257", - "cp1257": "windows1257", - "windows1258": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "win1258": "windows1258", - "cp1258": "windows1258", - "iso88591": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28591": "iso88591", - "iso88592": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "cp28592": "iso88592", - "iso88593": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" - }, - "cp28593": "iso88593", - "iso88594": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" - }, - "cp28594": "iso88594", - "iso88595": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" - }, - "cp28595": "iso88595", - "iso88596": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" - }, - "cp28596": "iso88596", - "iso88597": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "cp28597": "iso88597", - "iso88598": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "cp28598": "iso88598", - "iso88599": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "cp28599": "iso88599", - "iso885910": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" - }, - "cp28600": "iso885910", - "iso885911": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "cp28601": "iso885911", - "iso885913": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" - }, - "cp28603": "iso885913", - "iso885914": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" - }, - "cp28604": "iso885914", - "iso885915": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28605": "iso885915", - "iso885916": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" - }, - "cp28606": "iso885916", - "cp437": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm437": "cp437", - "csibm437": "cp437", - "cp737": { - "type": "_sbcs", - "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " - }, - "ibm737": "cp737", - "csibm737": "cp737", - "cp775": { - "type": "_sbcs", - "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " - }, - "ibm775": "cp775", - "csibm775": "cp775", - "cp850": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm850": "cp850", - "csibm850": "cp850", - "cp852": { - "type": "_sbcs", - "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " - }, - "ibm852": "cp852", - "csibm852": "cp852", - "cp855": { - "type": "_sbcs", - "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " - }, - "ibm855": "cp855", - "csibm855": "cp855", - "cp856": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm856": "cp856", - "csibm856": "cp856", - "cp857": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " - }, - "ibm857": "cp857", - "csibm857": "cp857", - "cp858": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm858": "cp858", - "csibm858": "cp858", - "cp860": { - "type": "_sbcs", - "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm860": "cp860", - "csibm860": "cp860", - "cp861": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm861": "cp861", - "csibm861": "cp861", - "cp862": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm862": "cp862", - "csibm862": "cp862", - "cp863": { - "type": "_sbcs", - "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm863": "cp863", - "csibm863": "cp863", - "cp864": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" - }, - "ibm864": "cp864", - "csibm864": "cp864", - "cp865": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm865": "cp865", - "csibm865": "cp865", - "cp866": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " - }, - "ibm866": "cp866", - "csibm866": "cp866", - "cp869": { - "type": "_sbcs", - "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " - }, - "ibm869": "cp869", - "csibm869": "cp869", - "cp922": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" - }, - "ibm922": "cp922", - "csibm922": "cp922", - "cp1046": { - "type": "_sbcs", - "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" - }, - "ibm1046": "cp1046", - "csibm1046": "cp1046", - "cp1124": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" - }, - "ibm1124": "cp1124", - "csibm1124": "cp1124", - "cp1125": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " - }, - "ibm1125": "cp1125", - "csibm1125": "cp1125", - "cp1129": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1129": "cp1129", - "csibm1129": "cp1129", - "cp1133": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" - }, - "ibm1133": "cp1133", - "csibm1133": "cp1133", - "cp1161": { - "type": "_sbcs", - "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " - }, - "ibm1161": "cp1161", - "csibm1161": "cp1161", - "cp1162": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "ibm1162": "cp1162", - "csibm1162": "cp1162", - "cp1163": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1163": "cp1163", - "csibm1163": "cp1163", - "maccroatian": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" - }, - "maccyrillic": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "macgreek": { - "type": "_sbcs", - "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" - }, - "maciceland": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macroman": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macromania": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macthai": { - "type": "_sbcs", - "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" - }, - "macturkish": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macukraine": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "koi8r": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8u": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8ru": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8t": { - "type": "_sbcs", - "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "armscii8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" - }, - "rk1048": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "tcvn": { - "type": "_sbcs", - "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" - }, - "georgianacademy": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "georgianps": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "pt154": { - "type": "_sbcs", - "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "viscii": { - "type": "_sbcs", - "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" - }, - "iso646cn": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "iso646jp": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "hproman8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" - }, - "macintosh": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "ascii": { - "type": "_sbcs", - "chars": "��������������������������������������������������������������������������������������������������������������������������������" - }, - "tis620": { - "type": "_sbcs", - "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - } -} - -/***/ }), - -/***/ 41080: -/***/ ((module) => { - -"use strict"; - - -// Manually added data to be used by sbcs codec in addition to generated one. +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; +var defineProperty = Object.defineProperty; +var gOPD = Object.getOwnPropertyDescriptor; -module.exports = { - // Not supported by iconv, not sure why. - "10029": "maccenteuro", - "maccenteuro": { - "type": "_sbcs", - "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" - }, +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } - "808": "cp808", - "ibm808": "cp808", - "cp808": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " - }, + return toStr.call(arr) === '[object Array]'; +}; - "mik": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } - // Aliases of generated encodings. - "ascii8bit": "ascii", - "usascii": "ascii", - "ansix34": "ascii", - "ansix341968": "ascii", - "ansix341986": "ascii", - "csascii": "ascii", - "cp367": "ascii", - "ibm367": "ascii", - "isoir6": "ascii", - "iso646us": "ascii", - "iso646irv": "ascii", - "us": "ascii", + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } - "latin1": "iso88591", - "latin2": "iso88592", - "latin3": "iso88593", - "latin4": "iso88594", - "latin5": "iso88599", - "latin6": "iso885910", - "latin7": "iso885913", - "latin8": "iso885914", - "latin9": "iso885915", - "latin10": "iso885916", + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } - "csisolatin1": "iso88591", - "csisolatin2": "iso88592", - "csisolatin3": "iso88593", - "csisolatin4": "iso88594", - "csisolatincyrillic": "iso88595", - "csisolatinarabic": "iso88596", - "csisolatingreek" : "iso88597", - "csisolatinhebrew": "iso88598", - "csisolatin5": "iso88599", - "csisolatin6": "iso885910", + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; - "l1": "iso88591", - "l2": "iso88592", - "l3": "iso88593", - "l4": "iso88594", - "l5": "iso88599", - "l6": "iso885910", - "l7": "iso885913", - "l8": "iso885914", - "l9": "iso885915", - "l10": "iso885916", +// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target +var setProperty = function setProperty(target, options) { + if (defineProperty && options.name === '__proto__') { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; + } +}; - "isoir14": "iso646jp", - "isoir57": "iso646cn", - "isoir100": "iso88591", - "isoir101": "iso88592", - "isoir109": "iso88593", - "isoir110": "iso88594", - "isoir144": "iso88595", - "isoir127": "iso88596", - "isoir126": "iso88597", - "isoir138": "iso88598", - "isoir148": "iso88599", - "isoir157": "iso885910", - "isoir166": "tis620", - "isoir179": "iso885913", - "isoir199": "iso885914", - "isoir203": "iso885915", - "isoir226": "iso885916", +// Return undefined instead of __proto__ if '__proto__' is not an own property +var getProperty = function getProperty(obj, name) { + if (name === '__proto__') { + if (!hasOwn.call(obj, name)) { + return void 0; + } else if (gOPD) { + // In early versions of node, obj['__proto__'] is buggy when obj has + // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. + return gOPD(obj, name).value; + } + } - "cp819": "iso88591", - "ibm819": "iso88591", + return obj[name]; +}; - "cyrillic": "iso88595", +module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; - "arabic": "iso88596", - "arabic8": "iso88596", - "ecma114": "iso88596", - "asmo708": "iso88596", + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } - "greek" : "iso88597", - "greek8" : "iso88597", - "ecma118" : "iso88597", - "elot928" : "iso88597", + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); - "hebrew": "iso88598", - "hebrew8": "iso88598", + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } - "turkish": "iso88599", - "turkish8": "iso88599", + // Never move original objects, clone them + setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); - "thai": "iso885911", - "thai8": "iso885911", + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + setProperty(target, { name: name, newValue: copy }); + } + } + } + } + } - "celtic": "iso885914", - "celtic8": "iso885914", - "isoceltic": "iso885914", + // Return the modified object + return target; +}; - "tis6200": "tis620", - "tis62025291": "tis620", - "tis62025330": "tis620", - "10000": "macroman", - "10006": "macgreek", - "10007": "maccyrillic", - "10079": "maciceland", - "10081": "macturkish", +/***/ }), - "cspc8codepage437": "cp437", - "cspc775baltic": "cp775", - "cspc850multilingual": "cp850", - "cspcp852": "cp852", - "cspc862latinhebrew": "cp862", - "cpgr": "cp869", +/***/ 87264: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - "msee": "cp1250", - "mscyrl": "cp1251", - "msansi": "cp1252", - "msgreek": "cp1253", - "msturk": "cp1254", - "mshebr": "cp1255", - "msarab": "cp1256", - "winbaltrim": "cp1257", +/* + * extsprintf.js: extended POSIX-style sprintf + */ - "cp20866": "koi8r", - "20866": "koi8r", - "ibm878": "koi8r", - "cskoi8r": "koi8r", +var mod_assert = __nccwpck_require__(39491); +var mod_util = __nccwpck_require__(73837); - "cp21866": "koi8u", - "21866": "koi8u", - "ibm1168": "koi8u", +/* + * Public interface + */ +exports.sprintf = jsSprintf; +exports.printf = jsPrintf; +exports.fprintf = jsFprintf; - "strk10482002": "rk1048", +/* + * Stripped down version of s[n]printf(3c). We make a best effort to throw an + * exception when given a format string we don't understand, rather than + * ignoring it, so that we won't break existing programs if/when we go implement + * the rest of this. + * + * This implementation currently supports specifying + * - field alignment ('-' flag), + * - zero-pad ('0' flag) + * - always show numeric sign ('+' flag), + * - field width + * - conversions for strings, decimal integers, and floats (numbers). + * - argument size specifiers. These are all accepted but ignored, since + * Javascript has no notion of the physical size of an argument. + * + * Everything else is currently unsupported, most notably precision, unsigned + * numbers, non-decimal numbers, and characters. + */ +function jsSprintf(fmt) +{ + var regex = [ + '([^%]*)', /* normal text */ + '%', /* start of format */ + '([\'\\-+ #0]*?)', /* flags (optional) */ + '([1-9]\\d*)?', /* width (optional) */ + '(\\.([1-9]\\d*))?', /* precision (optional) */ + '[lhjztL]*?', /* length mods (ignored) */ + '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ + ].join(''); - "tcvn5712": "tcvn", - "tcvn57121": "tcvn", + var re = new RegExp(regex); + var args = Array.prototype.slice.call(arguments, 1); + var flags, width, precision, conversion; + var left, pad, sign, arg, match; + var ret = ''; + var argn = 1; - "gb198880": "iso646cn", - "cn": "iso646cn", + mod_assert.equal('string', typeof (fmt)); - "csiso14jisc6220ro": "iso646jp", - "jisc62201969ro": "iso646jp", - "jp": "iso646jp", + while ((match = re.exec(fmt)) !== null) { + ret += match[1]; + fmt = fmt.substring(match[0].length); - "cshproman8": "hproman8", - "r8": "hproman8", - "roman8": "hproman8", - "xroman8": "hproman8", - "ibm1051": "hproman8", + flags = match[2] || ''; + width = match[3] || 0; + precision = match[4] || ''; + conversion = match[6]; + left = false; + sign = false; + pad = ' '; - "mac": "macintosh", - "csmacintosh": "macintosh", -}; + if (conversion == '%') { + ret += '%'; + continue; + } + if (args.length === 0) + throw (new Error('too few args to sprintf')); + arg = args.shift(); + argn++; -/***/ }), + if (flags.match(/[\' #]/)) + throw (new Error( + 'unsupported flags: ' + flags)); -/***/ 11155: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (precision.length > 0) + throw (new Error( + 'non-zero precision not supported')); -"use strict"; + if (flags.match(/-/)) + left = true; -var Buffer = __nccwpck_require__(15118).Buffer; + if (flags.match(/0/)) + pad = '0'; -// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + if (flags.match(/\+/)) + sign = true; -// == UTF16-BE codec. ========================================================== + switch (conversion) { + case 's': + if (arg === undefined || arg === null) + throw (new Error('argument ' + argn + + ': attempted to print undefined or null ' + + 'as a string')); + ret += doPad(pad, width, left, arg.toString()); + break; -exports.utf16be = Utf16BECodec; -function Utf16BECodec() { -} + case 'd': + arg = Math.floor(arg); + /*jsl:fallthru*/ + case 'f': + sign = sign && arg > 0 ? '+' : ''; + ret += sign + doPad(pad, width, left, + arg.toString()); + break; -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; + case 'x': + ret += doPad(pad, width, left, arg.toString(16)); + break; + case 'j': /* non-standard */ + if (width === 0) + width = 10; + ret += mod_util.inspect(arg, false, width); + break; -// -- Encoding + case 'r': /* non-standard */ + ret += dumpException(arg); + break; -function Utf16BEEncoder() { -} + default: + throw (new Error('unsupported conversion: ' + + conversion)); + } + } -Utf16BEEncoder.prototype.write = function(str) { - var buf = Buffer.from(str, 'ucs2'); - for (var i = 0; i < buf.length; i += 2) { - var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; - } - return buf; + ret += fmt; + return (ret); } -Utf16BEEncoder.prototype.end = function() { +function jsPrintf() { + var args = Array.prototype.slice.call(arguments); + args.unshift(process.stdout); + jsFprintf.apply(null, args); } - -// -- Decoding - -function Utf16BEDecoder() { - this.overflowByte = -1; +function jsFprintf(stream) { + var args = Array.prototype.slice.call(arguments, 1); + return (stream.write(jsSprintf.apply(this, args))); } -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; - - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; - - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; - } - - for (; i < buf.length-1; i += 2, j+= 2) { - buf2[j] = buf[i+1]; - buf2[j+1] = buf[i]; - } +function doPad(chr, width, left, str) +{ + var ret = str; - this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + while (ret.length < width) { + if (left) + ret += chr; + else + ret = chr + ret; + } - return buf2.slice(0, j).toString('ucs2'); + return (ret); } -Utf16BEDecoder.prototype.end = function() { -} +/* + * This function dumps long stack traces for exceptions having a cause() method. + * See node-verror for an example. + */ +function dumpException(ex) +{ + var ret; + if (!(ex instanceof Error)) + throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); -// == UTF-16 codec ============================================================= -// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. -// Defaults to UTF-16LE, as it's prevalent and default in Node. -// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le -// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + /* Note that V8 prepends "ex.stack" with ex.toString(). */ + ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; -// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + if (ex.cause && typeof (ex.cause) === 'function') { + var cex = ex.cause(); + if (cex) { + ret += '\nCaused by: ' + dumpException(cex); + } + } -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; + return (ret); } -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; - -// -- Encoding (pass-through) +/***/ }), -function Utf16Encoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; - this.encoder = codec.iconv.getEncoder('utf-16le', options); -} +/***/ 28206: +/***/ ((module) => { -Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); -} +"use strict"; -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); -} +// do not edit .js files directly - edit src/index.jst -// -- Decoding -function Utf16Decoder(options, codec) { - this.decoder = null; - this.initialBytes = []; - this.initialBytesLen = 0; - this.options = options || {}; - this.iconv = codec.iconv; -} +module.exports = function equal(a, b) { + if (a === b) return true; -Utf16Decoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBytes.push(buf); - this.initialBytesLen += buf.length; - - if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) - return ''; + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; - // We have enough bytes -> detect endianness. - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - this.initialBytes.length = this.initialBytesLen = 0; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; } - return this.decoder.write(buf); -} - -Utf16Decoder.prototype.end = function() { - if (!this.decoder) { - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - var res = this.decoder.write(buf), - trail = this.decoder.end(); - return trail ? (res + trail) : res; - } - return this.decoder.end(); -} + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); -function detectEncoding(buf, defaultEncoding) { - var enc = defaultEncoding || 'utf-16le'; + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; - if (buf.length >= 2) { - // Check BOM. - if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM - enc = 'utf-16be'; - else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM - enc = 'utf-16le'; - else { - // No BOM found. Try to deduce encoding from initial content. - // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. - // So, we count ASCII as if it was LE or BE, and decide from that. - var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions - _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (var i = 0; i < _len; i += 2) { - if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; - if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; - } + for (i = length; i-- !== 0;) { + var key = keys[i]; - if (asciiCharsBE > asciiCharsLE) - enc = 'utf-16be'; - else if (asciiCharsBE < asciiCharsLE) - enc = 'utf-16le'; - } + if (!equal(a[key], b[key])) return false; } - return enc; -} - + return true; + } + // true if both NaN, false otherwise + return a!==a && b!==b; +}; /***/ }), -/***/ 51644: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 30969: +/***/ ((module) => { "use strict"; -var Buffer = __nccwpck_require__(15118).Buffer; -// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 -// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 +module.exports = function (data, opts) { + if (!opts) opts = {}; + if (typeof opts === 'function') opts = { cmp: opts }; + var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; -exports.utf7 = Utf7Codec; -exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 -function Utf7Codec(codecOptions, iconv) { - this.iconv = iconv; -}; + var cmp = opts.cmp && (function (f) { + return function (node) { + return function (a, b) { + var aobj = { key: a, value: node[a] }; + var bobj = { key: b, value: node[b] }; + return f(aobj, bobj); + }; + }; + })(opts.cmp); -Utf7Codec.prototype.encoder = Utf7Encoder; -Utf7Codec.prototype.decoder = Utf7Decoder; -Utf7Codec.prototype.bomAware = true; + var seen = []; + return (function stringify (node) { + if (node && node.toJSON && typeof node.toJSON === 'function') { + node = node.toJSON(); + } + if (node === undefined) return; + if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; + if (typeof node !== 'object') return JSON.stringify(node); -// -- Encoding + var i, out; + if (Array.isArray(node)) { + out = '['; + for (i = 0; i < node.length; i++) { + if (i) out += ','; + out += stringify(node[i]) || 'null'; + } + return out + ']'; + } -var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + if (node === null) return 'null'; -function Utf7Encoder(options, codec) { - this.iconv = codec.iconv; -} + if (seen.indexOf(node) !== -1) { + if (cycles) return JSON.stringify('__cycle__'); + throw new TypeError('Converting circular structure to JSON'); + } -Utf7Encoder.prototype.write = function(str) { - // Naive implementation. - // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". - return Buffer.from(str.replace(nonDirectChars, function(chunk) { - return "+" + (chunk === '+' ? '' : - this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) - + "-"; - }.bind(this))); -} + var seenIndex = seen.push(node) - 1; + var keys = Object.keys(node).sort(cmp && cmp(node)); + out = ''; + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = stringify(node[key]); -Utf7Encoder.prototype.end = function() { -} + if (!value) continue; + if (out) out += ','; + out += JSON.stringify(key) + ':' + value; + } + seen.splice(seenIndex, 1); + return '{' + out + '}'; + })(data); +}; -// -- Decoding +/***/ }), -function Utf7Decoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} +/***/ 31133: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var base64Regex = /[A-Za-z0-9\/+]/; -var base64Chars = []; -for (var i = 0; i < 256; i++) - base64Chars[i] = base64Regex.test(String.fromCharCode(i)); +var debug; -var plusChar = '+'.charCodeAt(0), - minusChar = '-'.charCodeAt(0), - andChar = '&'.charCodeAt(0); +module.exports = function () { + if (!debug) { + try { + /* eslint global-require: off */ + debug = __nccwpck_require__(38237)("follow-redirects"); + } + catch (error) { + debug = function () { /* */ }; + } + } + debug.apply(null, arguments); +}; -Utf7Decoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; - // The decoder is more involved as we must handle chunks in stream. +/***/ }), - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '+' - if (buf[i] == plusChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64Chars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" - res += "+"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString(); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } +/***/ 67707: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (buf[i] != minusChar) // Minus is absorbed after base64. - i--; +var url = __nccwpck_require__(57310); +var URL = url.URL; +var http = __nccwpck_require__(13685); +var https = __nccwpck_require__(22241); +var Writable = (__nccwpck_require__(12781).Writable); +var assert = __nccwpck_require__(39491); +var debug = __nccwpck_require__(31133); - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } - } +// Create handlers that pass events from native requests +var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; +var eventHandlers = Object.create(null); +events.forEach(function (event) { + eventHandlers[event] = function (arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; +}); - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString(); +// Error types with codes +var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "" +); +var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded" +); +var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" +); +var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" +); - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); +// An HTTP(S) request that can be redirected +function RedirectableRequest(options, responseCallback) { + // Initialize the request + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } + // Attach a callback if passed + if (responseCallback) { + this.on("response", responseCallback); + } - this.inBase64 = inBase64; - this.base64Accum = base64Accum; + // React to responses of native requests + var self = this; + this._onNativeResponse = function (response) { + self._processResponse(response); + }; - return res; + // Perform the first request + this._performRequest(); } +RedirectableRequest.prototype = Object.create(Writable.prototype); -Utf7Decoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - - this.inBase64 = false; - this.base64Accum = ''; - return res; -} - - -// UTF-7-IMAP codec. -// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) -// Differences: -// * Base64 part is started by "&" instead of "+" -// * Direct characters are 0x20-0x7E, except "&" (0x26) -// * In Base64, "," is used instead of "/" -// * Base64 must not be used to represent direct characters. -// * No implicit shift back from Base64 (should always end with '-') -// * String must end in non-shifted position. -// * "-&" while in base64 is not allowed. - +RedirectableRequest.prototype.abort = function () { + // Abort the internal request + abortRequest(this._currentRequest); -exports.utf7imap = Utf7IMAPCodec; -function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; + // Abort this request + this.emit("abort"); + this.removeAllListeners(); }; -Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; -Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; -Utf7IMAPCodec.prototype.bomAware = true; +// Writes buffered data to the current native request +RedirectableRequest.prototype.write = function (data, encoding, callback) { + // Writing is not allowed if end has been called + if (this._ending) { + throw new WriteAfterEndError(); + } + // Validate input and shift parameters if necessary + if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } -// -- Encoding + // Ignore empty buffers, since writing them doesn't invoke the callback + // https://github.com/nodejs/node/issues/22066 + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + // Only write when we don't exceed the maximum body length + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data: data, encoding: encoding }); + this._currentRequest.write(data, encoding, callback); + } + // Error when we exceed the maximum body length + else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); + } +}; -function Utf7IMAPEncoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = Buffer.alloc(6); - this.base64AccumIdx = 0; -} +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (typeof data === "function") { + callback = data; + data = encoding = null; + } + else if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } -Utf7IMAPEncoder.prototype.write = function(str) { - var inBase64 = this.inBase64, - base64Accum = this.base64Accum, - base64AccumIdx = this.base64AccumIdx, - buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + // Write data if needed and end + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } + else { + var self = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function () { + self._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; + } +}; - for (var i = 0; i < str.length; i++) { - var uChar = str.charCodeAt(i); - if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. - if (inBase64) { - if (base64AccumIdx > 0) { - bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - base64AccumIdx = 0; - } +// Sets a header value on the current native request +RedirectableRequest.prototype.setHeader = function (name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); +}; - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - inBase64 = false; - } +// Clears a header value on the current native request +RedirectableRequest.prototype.removeHeader = function (name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); +}; - if (!inBase64) { - buf[bufIdx++] = uChar; // Write direct character +// Global timeout for all underlying requests +RedirectableRequest.prototype.setTimeout = function (msecs, callback) { + var self = this; + if (callback) { + this.on("timeout", callback); + } - if (uChar === andChar) // Ampersand -> '&-' - buf[bufIdx++] = minusChar; - } + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } - } else { // Non-direct character - if (!inBase64) { - buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. - inBase64 = true; - } - if (inBase64) { - base64Accum[base64AccumIdx++] = uChar >> 8; - base64Accum[base64AccumIdx++] = uChar & 0xFF; + // Sets up a timer to trigger a timeout event + function startTimer(socket) { + if (self._timeout) { + clearTimeout(self._timeout); + } + self._timeout = setTimeout(function () { + self.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } - if (base64AccumIdx == base64Accum.length) { - bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); - base64AccumIdx = 0; - } - } - } + // Prevent a timeout from triggering + function clearTimer() { + clearTimeout(this._timeout); + if (callback) { + self.removeListener("timeout", callback); + } + if (!this.socket) { + self._currentRequest.removeListener("socket", startTimer); } + } - this.inBase64 = inBase64; - this.base64AccumIdx = base64AccumIdx; + // Start the timer when the socket is opened + if (this.socket) { + startTimer(this.socket); + } + else { + this._currentRequest.once("socket", startTimer); + } - return buf.slice(0, bufIdx); -} + this.on("socket", destroyOnTimeout); + this.once("response", clearTimer); + this.once("error", clearTimer); -Utf7IMAPEncoder.prototype.end = function() { - var buf = Buffer.alloc(10), bufIdx = 0; - if (this.inBase64) { - if (this.base64AccumIdx > 0) { - bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - this.base64AccumIdx = 0; - } + return this; +}; - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - this.inBase64 = false; - } +// Proxy all other public ClientRequest methods +[ + "flushHeaders", "getHeader", + "setNoDelay", "setSocketKeepAlive", +].forEach(function (method) { + RedirectableRequest.prototype[method] = function (a, b) { + return this._currentRequest[method](a, b); + }; +}); - return buf.slice(0, bufIdx); -} +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); +RedirectableRequest.prototype._sanitizeOptions = function (options) { + // Ensure headers are always present + if (!options.headers) { + options.headers = {}; + } -// -- Decoding + // Since http.request treats host as an alias of hostname, + // but the url module interprets host as hostname plus port, + // eliminate the host property to avoid confusion. + if (options.host) { + // Use hostname if set, because it has precedence + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } -function Utf7IMAPDecoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} + // Complete the URL object when necessary + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } + else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } +}; -var base64IMAPChars = base64Chars.slice(); -base64IMAPChars[','.charCodeAt(0)] = true; -Utf7IMAPDecoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; +// Executes the next native request (initial or redirect) +RedirectableRequest.prototype._performRequest = function () { + // Load the native protocol + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + this.emit("error", new TypeError("Unsupported protocol " + protocol)); + return; + } - // The decoder is more involved as we must handle chunks in stream. - // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + // If specified, use the agent corresponding to the protocol + // (HTTP and HTTPS use different types of agents) + if (this._options.agents) { + var scheme = protocol.substr(0, protocol.length - 1); + this._options.agent = this._options.agents[scheme]; + } - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '&' - if (buf[i] == andChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64IMAPChars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" - res += "&"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } + // Create the native request + var request = this._currentRequest = + nativeProtocol.request(this._options, this._onNativeResponse); + this._currentUrl = url.format(this._options); - if (buf[i] != minusChar) // Minus may be absorbed after base64. - i--; + // Set up event handlers + request._redirectable = this; + for (var e = 0; e < events.length; e++) { + request.on(events[e], eventHandlers[events[e]]); + } - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } + // End a redirected request + // (The first request must be ended explicitly with RedirectableRequest#end) + if (this._isRedirect) { + // Write the request entity and end. + var i = 0; + var self = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + // Only write if this request has not been redirected yet + /* istanbul ignore else */ + if (request === self._currentRequest) { + // Report any write errors + /* istanbul ignore if */ + if (error) { + self.emit("error", error); } - } + // Write the next buffer if there are still left + else if (i < buffers.length) { + var buffer = buffers[i++]; + /* istanbul ignore else */ + if (!request.finished) { + request.write(buffer.data, buffer.encoding, writeNext); + } + } + // End the request if `end` has been called on us + else if (self._ended) { + request.end(); + } + } + }()); + } +}; - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); +// Processes a response from the current native request +RedirectableRequest.prototype._processResponse = function (response) { + // Store the redirected response + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode: statusCode, + }); + } - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); + // RFC7231§6.4: The 3xx (Redirection) class of status code indicates + // that further action needs to be taken by the user agent in order to + // fulfill the request. If a Location header field is provided, + // the user agent MAY automatically redirect its request to the URI + // referenced by the Location field value, + // even if the specific status code is not understood. + var location = response.headers.location; + if (location && this._options.followRedirects !== false && + statusCode >= 300 && statusCode < 400) { + // Abort the current request + abortRequest(this._currentRequest); + // Discard the remainder of the response to avoid waiting for data + response.destroy(); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + // RFC7231§6.4: A client SHOULD detect and intervene + // in cyclical redirections (i.e., "infinite" redirection loops). + if (++this._redirectCount > this._options.maxRedirects) { + this.emit("error", new TooManyRedirectsError()); + return; } - this.inBase64 = inBase64; - this.base64Accum = base64Accum; - - return res; -} - -Utf7IMAPDecoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + // RFC7231§6.4: Automatic redirection needs to done with + // care for methods not known to be safe, […] + // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change + // the request method from POST to GET for the subsequent request. + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || + // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + // Drop a possible entity and headers related to it + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } - this.inBase64 = false; - this.base64Accum = ''; - return res; -} + // Drop the Host header, as the redirect might lead to a different host + var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) || + url.parse(this._currentUrl).hostname; + // Create the redirected request + var redirectUrl = url.resolve(this._currentUrl, location); + debug("redirecting to", redirectUrl); + this._isRedirect = true; + var redirectUrlParts = url.parse(redirectUrl); + Object.assign(this._options, redirectUrlParts); + // Drop the Authorization header if redirecting to another host + if (redirectUrlParts.hostname !== previousHostName) { + removeMatchingHeaders(/^authorization$/i, this._options.headers); + } + // Evaluate the beforeRedirect callback + if (typeof this._options.beforeRedirect === "function") { + var responseDetails = { headers: response.headers }; + try { + this._options.beforeRedirect.call(null, this._options, responseDetails); + } + catch (err) { + this.emit("error", err); + return; + } + this._sanitizeOptions(this._options); + } -/***/ }), + // Perform the redirected request + try { + this._performRequest(); + } + catch (cause) { + var error = new RedirectionError("Redirected request failed: " + cause.message); + error.cause = cause; + this.emit("error", error); + } + } + else { + // The response is not a redirect; return it as-is + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); -/***/ 67961: -/***/ ((__unused_webpack_module, exports) => { + // Clean up + this._requestBodyBuffers = []; + } +}; -"use strict"; +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; + // Wrap each protocol + var nativeProtocols = {}; + Object.keys(protocols).forEach(function (scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); -var BOMChar = '\uFEFF'; + // Executes a request, following redirects + function request(input, options, callback) { + // Parse parameters + if (typeof input === "string") { + var urlStr = input; + try { + input = urlToOptions(new URL(urlStr)); + } + catch (err) { + /* istanbul ignore next */ + input = url.parse(urlStr); + } + } + else if (URL && (input instanceof URL)) { + input = urlToOptions(input); + } + else { + callback = options; + options = input; + input = { protocol: protocol }; + } + if (typeof options === "function") { + callback = options; + options = null; + } -exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; -} + // Set defaults + options = Object.assign({ + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, input, options); + options.nativeProtocols = nativeProtocols; -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); } - return this.encoder.write(str); -} + // Executes a GET request, following redirects + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); + // Expose the properties on the wrapped protocol + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true }, + }); + }); + return exports; } +/* istanbul ignore next */ +function noop() { /* empty */ } -//------------------------------------------------------------------------------ - -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; +// from https://github.com/nodejs/node/blob/master/lib/internal/url.js +function urlToOptions(urlObject) { + var options = { + protocol: urlObject.protocol, + hostname: urlObject.hostname.startsWith("[") ? + /* istanbul ignore next */ + urlObject.hostname.slice(1, -1) : + urlObject.hostname, + hash: urlObject.hash, + search: urlObject.search, + pathname: urlObject.pathname, + path: urlObject.pathname + urlObject.search, + href: urlObject.href, + }; + if (urlObject.port !== "") { + options.port = Number(urlObject.port); + } + return options; } -StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) - return res; - - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === 'function') - this.options.stripBOM(); +function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; } + } + return lastValue; +} - this.pass = true; - return res; +function createErrorType(code, defaultMessage) { + function CustomError(message) { + Error.captureStackTrace(this, this.constructor); + this.message = message || defaultMessage; + } + CustomError.prototype = new Error(); + CustomError.prototype.constructor = CustomError; + CustomError.prototype.name = "Error [" + code + "]"; + CustomError.prototype.code = code; + return CustomError; } -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); +function abortRequest(request) { + for (var e = 0; e < events.length; e++) { + request.removeListener(events[e], eventHandlers[events[e]]); + } + request.on("error", noop); + request.abort(); } +// Exports +module.exports = wrap({ http: http, https: https }); +module.exports.wrap = wrap; /***/ }), -/***/ 30393: +/***/ 47568: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - -var Buffer = __nccwpck_require__(64293).Buffer; -// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer +module.exports = ForeverAgent +ForeverAgent.SSL = ForeverAgentSSL -// == Extend Node primitives to use iconv-lite ================================= +var util = __nccwpck_require__(73837) + , Agent = (__nccwpck_require__(13685).Agent) + , net = __nccwpck_require__(41808) + , tls = __nccwpck_require__(24404) + , AgentSSL = (__nccwpck_require__(22241).Agent) + +function getConnectionName(host, port) { + var name = '' + if (typeof host === 'string') { + name = host + ':' + port + } else { + // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name. + name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':') + } + return name +} -module.exports = function (iconv) { - var original = undefined; // Place to keep original methods. +function ForeverAgent(options) { + var self = this + self.options = options || {} + self.requests = {} + self.sockets = {} + self.freeSockets = {} + self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets + self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets + self.on('free', function(socket, host, port) { + var name = getConnectionName(host, port) - // Node authors rewrote Buffer internals to make it compatible with - // Uint8Array and we cannot patch key functions since then. - // Note: this does use older Buffer API on a purpose - iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); + if (self.requests[name] && self.requests[name].length) { + self.requests[name].shift().onSocket(socket) + } else if (self.sockets[name].length < self.minSockets) { + if (!self.freeSockets[name]) self.freeSockets[name] = [] + self.freeSockets[name].push(socket) + + // if an error happens while we don't use the socket anyway, meh, throw the socket away + var onIdleError = function() { + socket.destroy() + } + socket._onIdleError = onIdleError + socket.on('error', onIdleError) + } else { + // If there are no pending requests just destroy the + // socket and it will get removed from the pool. This + // gets us out of timeout issues and allows us to + // default to Connection:keep-alive. + socket.destroy() + } + }) - iconv.extendNodeEncodings = function extendNodeEncodings() { - if (original) return; - original = {}; +} +util.inherits(ForeverAgent, Agent) - if (!iconv.supportsNodeEncodingsExtension) { - console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); - console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); - return; - } +ForeverAgent.defaultMinSockets = 5 - var nodeNativeEncodings = { - 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, - 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, - }; - Buffer.isNativeEncoding = function(enc) { - return enc && nodeNativeEncodings[enc.toLowerCase()]; - } +ForeverAgent.prototype.createConnection = net.createConnection +ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest +ForeverAgent.prototype.addRequest = function(req, host, port) { + var name = getConnectionName(host, port) + + if (typeof host !== 'string') { + var options = host + port = options.port + host = options.host + } - // -- SlowBuffer ----------------------------------------------------------- - var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; + if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { + var idleSocket = this.freeSockets[name].pop() + idleSocket.removeListener('error', idleSocket._onIdleError) + delete idleSocket._onIdleError + req._reusedSocket = true + req.onSocket(idleSocket) + } else { + this.addRequestNoreuse(req, host, port) + } +} - original.SlowBufferToString = SlowBuffer.prototype.toString; - SlowBuffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); +ForeverAgent.prototype.removeSocket = function(s, name, host, port) { + if (this.sockets[name]) { + var index = this.sockets[name].indexOf(s) + if (index !== -1) { + this.sockets[name].splice(index, 1) + } + } else if (this.sockets[name] && this.sockets[name].length === 0) { + // don't leak + delete this.sockets[name] + delete this.requests[name] + } + + if (this.freeSockets[name]) { + var index = this.freeSockets[name].indexOf(s) + if (index !== -1) { + this.freeSockets[name].splice(index, 1) + if (this.freeSockets[name].length === 0) { + delete this.freeSockets[name] + } + } + } - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferToString.call(this, encoding, start, end); + if (this.requests[name] && this.requests[name].length) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(name, host, port).emit('free') + } +} - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); - } +function ForeverAgentSSL (options) { + ForeverAgent.call(this, options) +} +util.inherits(ForeverAgentSSL, ForeverAgent) - original.SlowBufferWrite = SlowBuffer.prototype.write; - SlowBuffer.prototype.write = function(string, offset, length, encoding) { - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } +ForeverAgentSSL.prototype.createConnection = createConnectionSSL +ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } - encoding = String(encoding || 'utf8').toLowerCase(); +function createConnectionSSL (port, host, options) { + if (typeof port === 'object') { + options = port; + } else if (typeof host === 'object') { + options = host; + } else if (typeof options === 'object') { + options = options; + } else { + options = {}; + } - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferWrite.call(this, string, offset, length, encoding); + if (typeof port === 'number') { + options.port = port; + } - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); + if (typeof host === 'string') { + options.host = host; + } - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; - } + return tls.connect(options); +} - // -- Buffer --------------------------------------------------------------- - original.BufferIsEncoding = Buffer.isEncoding; - Buffer.isEncoding = function(encoding) { - return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); - } +/***/ }), - original.BufferByteLength = Buffer.byteLength; - Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { - encoding = String(encoding || 'utf8').toLowerCase(); +/***/ 64334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferByteLength.call(this, str, encoding); +var CombinedStream = __nccwpck_require__(85443); +var util = __nccwpck_require__(73837); +var path = __nccwpck_require__(71017); +var http = __nccwpck_require__(13685); +var https = __nccwpck_require__(22241); +var parseUrl = (__nccwpck_require__(57310).parse); +var fs = __nccwpck_require__(57147); +var mime = __nccwpck_require__(43583); +var asynckit = __nccwpck_require__(14812); +var populate = __nccwpck_require__(17142); - // Slow, I know, but we don't have a better way yet. - return iconv.encode(str, encoding).length; - } +// Public API +module.exports = FormData; - original.BufferToString = Buffer.prototype.toString; - Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); +// make it a Stream +util.inherits(FormData, CombinedStream); - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferToString.call(this, encoding, start, end); +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(); + } - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); - } + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; - original.BufferWrite = Buffer.prototype.write; - Buffer.prototype.write = function(string, offset, length, encoding) { - var _offset = offset, _length = length, _encoding = encoding; - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } + CombinedStream.call(this); - encoding = String(encoding || 'utf8').toLowerCase(); + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } +} - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferWrite.call(this, string, _offset, _length, _encoding); +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } +FormData.prototype.append = function(field, value, options) { - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); + options = options || {}; - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; + } - // TODO: Set _charsWritten. - } + var append = CombinedStream.prototype.append.bind(this); + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; + } - // -- Readable ------------------------------------------------------------- - if (iconv.supportsStreams) { - var Readable = __nccwpck_require__(92413).Readable; + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; + } - original.ReadableSetEncoding = Readable.prototype.setEncoding; - Readable.prototype.setEncoding = function setEncoding(enc, options) { - // Use our own decoder, it has the same interface. - // We cannot use original function as it doesn't handle BOM-s. - this._readableState.decoder = iconv.getDecoder(enc, options); - this._readableState.encoding = enc; - } + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); - Readable.prototype.collect = iconv._collect; - } - } + append(header); + append(value); + append(footer); - // Remove iconv-lite Node primitive extensions. - iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { - if (!iconv.supportsNodeEncodingsExtension) - return; - if (!original) - throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + // pass along options.knownLength + this._trackLength(header, value, options); +}; - delete Buffer.isNativeEncoding; +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; - var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } - SlowBuffer.prototype.toString = original.SlowBufferToString; - SlowBuffer.prototype.write = original.SlowBufferWrite; + this._valueLength += valueLength; - Buffer.isEncoding = original.BufferIsEncoding; - Buffer.byteLength = original.BufferByteLength; - Buffer.prototype.toString = original.BufferToString; - Buffer.prototype.write = original.BufferWrite; + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; - if (iconv.supportsStreams) { - var Readable = __nccwpck_require__(92413).Readable; + // empty or either doesn't have path or not an http response + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { + return; + } - Readable.prototype.setEncoding = original.ReadableSetEncoding; - delete Readable.prototype.collect; - } + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; - original = undefined; - } -} +FormData.prototype._lengthRetriever = function(value, callback) { + if (value.hasOwnProperty('fd')) { -/***/ }), + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { -/***/ 19032: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); -"use strict"; + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { + var fileSize; -// Some environments don't have global Buffer (e.g. React Native). -// Solution would be installing npm modules "buffer" and "stream" explicitly. -var Buffer = __nccwpck_require__(15118).Buffer; + if (err) { + callback(err); + return; + } -var bomHandling = __nccwpck_require__(67961), - iconv = module.exports; + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } -// All codecs and aliases are kept here, keyed by encoding name/alias. -// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. -iconv.encodings = null; + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); -// Characters emitted in case of error. -iconv.defaultCharUnicode = '�'; -iconv.defaultCharSingleByte = '?'; + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); -// Public API. -iconv.encode = function encode(str, encoding, options) { - str = "" + (str || ""); // Ensure string. - - var encoder = iconv.getEncoder(encoding, options); + // something else + } else { + callback('Unknown stream'); + } +}; - var res = encoder.write(str); - var trail = encoder.end(); - - return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; -} +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; + } -iconv.decode = function decode(buf, encoding, options) { - if (typeof buf === 'string') { - if (!iconv.skipDecodeWarning) { - console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); - iconv.skipDecodeWarning = true; - } + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); - buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. - } + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; - var decoder = iconv.getDecoder(encoding, options); + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); + } - var res = decoder.write(buf); - var trail = decoder.end(); + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; - return trail ? (res + trail) : res; -} + // skip nullish headers. + if (header == null) { + continue; + } -iconv.encodingExists = function encodingExists(enc) { - try { - iconv.getCodec(enc); - return true; - } catch (e) { - return false; + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; } -} -// Legacy aliases to convert functions -iconv.toEncoding = iconv.encode; -iconv.fromEncoding = iconv.decode; + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } + } -// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. -iconv._codecDataCache = {}; -iconv.getCodec = function getCodec(encoding) { - if (!iconv.encodings) - iconv.encodings = __nccwpck_require__(82733); // Lazy load all encoding definitions. - - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - var enc = iconv._canonicalizeEncoding(encoding); + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; - // Traverse iconv.encodings to find actual codec. - var codecOptions = {}; - while (true) { - var codec = iconv._codecDataCache[enc]; - if (codec) - return codec; +FormData.prototype._getContentDisposition = function(value, options) { - var codecDef = iconv.encodings[enc]; + var filename + , contentDisposition + ; - switch (typeof codecDef) { - case "string": // Direct alias to other encoding. - enc = codecDef; - break; + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path); + } - case "object": // Alias with options. Can be layered. - for (var key in codecDef) - codecOptions[key] = codecDef[key]; + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - enc = codecDef.type; - break; + return contentDisposition; +}; - case "function": // Codec itself. - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; +FormData.prototype._getContentType = function(value, options) { - // The codec function must load all tables and return object with .encoder and .decoder methods. - // It'll be called only once (for each different options object). - codec = new codecDef(codecOptions, iconv); + // use custom content-type above all + var contentType = options.contentType; - iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. - return codec; + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); + } - default: - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); - } - } -} + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } -iconv._canonicalizeEncoding = function(encoding) { - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); -} + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; + } -iconv.getEncoder = function getEncoder(encoding, options) { - var codec = iconv.getCodec(encoding), - encoder = new codec.encoder(options, codec); + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } - if (codec.bomAware && options && options.addBOM) - encoder = new bomHandling.PrependBOM(encoder, options); + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } - return encoder; -} + return contentType; +}; -iconv.getDecoder = function getDecoder(encoding, options) { - var codec = iconv.getCodec(encoding), - decoder = new codec.decoder(options, codec); +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; - if (codec.bomAware && !(options && options.stripBOM === false)) - decoder = new bomHandling.StripBOM(decoder, options); + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } - return decoder; -} + next(footer); + }.bind(this); +}; +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; -// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. -var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; -if (nodeVer) { +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; - // Load streaming support in Node v0.10+ - var nodeVerArr = nodeVer.split(".").map(Number); - if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { - __nccwpck_require__(76409)(iconv); + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; } + } - // Load Node primitive extensions. - __nccwpck_require__(30393)(iconv); -} - -if (false) {} - + return formHeaders; +}; -/***/ }), +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } -/***/ 76409: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this._boundary; +}; -"use strict"; +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } + this._boundary = boundary; +}; -var Buffer = __nccwpck_require__(64293).Buffer, - Transform = __nccwpck_require__(92413).Transform; +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } -// == Exports ================================================================== -module.exports = function(iconv) { - - // Additional Public API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); - } + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } - iconv.decodeStream = function decodeStream(encoding, options) { - return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); - } + return knownLength; +}; - iconv.supportsStreams = true; +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } - // Not published yet. - iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; - iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; - iconv._collect = IconvLiteDecoderStream.prototype.collect; + return hasKnownLength; }; +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; -// == Encoder stream ======================================================= -function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; // We accept only strings, so we don't need to decode them. - Transform.call(this, options); -} - -IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } -}); + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } -IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk != 'string') - return done(new Error("Iconv encoding stream needs strings as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } -} + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } -IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; } -} -IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on('error', cb); - this.on('data', function(chunk) { chunks.push(chunk); }); - this.on('end', function() { - cb(null, Buffer.concat(chunks)); + values.forEach(function(length) { + knownLength += length; }); - return this; -} + cb(null, knownLength); + }); +}; -// == Decoder stream ======================================================= -function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); -} +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; -IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } -}); + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { -IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer.isBuffer(chunk)) - return done(new Error("Iconv decoding stream needs buffers as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); + + // use custom params + } else { + + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; } -} + } -IconvLiteDecoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); + + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } + + // get content length and fire away + this.getLength(function(err, length) { + if (err) { + this._error(err); + return; } - catch (e) { - done(e); + + // add content length + request.setHeader('Content-Length', length); + + this.pipe(request); + if (cb) { + request.on('error', cb); + request.on('response', cb.bind(this, null)); } -} + }.bind(this)); -IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ''; - this.on('error', cb); - this.on('data', function(chunk) { res += chunk; }); - this.on('end', function() { - cb(null, res); - }); - return this; -} + return request; +}; + +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); + } +}; +FormData.prototype.toString = function () { + return '[object FormData]'; +}; /***/ }), -/***/ 42469: +/***/ 17142: /***/ ((module) => { -// Generated using `npm run build`. Do not edit. +// populates missing values +module.exports = function(dst, src) { -var regex = /^[a-z](?:[\.0-9_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*-(?:[\x2D\.0-9_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*$/; + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); -var isPotentialCustomElementName = function(string) { - return regex.test(string); + return dst; }; -module.exports = isPotentialCustomElementName; + +/***/ }), + +/***/ 13679: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +module.exports = { + afterRequest: __nccwpck_require__(83932), + beforeRequest: __nccwpck_require__(36136), + browser: __nccwpck_require__(805), + cache: __nccwpck_require__(51632), + content: __nccwpck_require__(61567), + cookie: __nccwpck_require__(25725), + creator: __nccwpck_require__(47218), + entry: __nccwpck_require__(74560), + har: __nccwpck_require__(75579), + header: __nccwpck_require__(75147), + log: __nccwpck_require__(53013), + page: __nccwpck_require__(34777), + pageTimings: __nccwpck_require__(5538), + postData: __nccwpck_require__(12096), + query: __nccwpck_require__(21251), + request: __nccwpck_require__(99646), + response: __nccwpck_require__(9103), + timings: __nccwpck_require__(22007) +} /***/ }), -/***/ 10657: +/***/ 74944: /***/ ((module) => { -module.exports = isTypedArray -isTypedArray.strict = isStrictTypedArray -isTypedArray.loose = isLooseTypedArray +function HARError (errors) { + var message = 'validation failed' -var toString = Object.prototype.toString -var names = { - '[object Int8Array]': true - , '[object Int16Array]': true - , '[object Int32Array]': true - , '[object Uint8Array]': true - , '[object Uint8ClampedArray]': true - , '[object Uint16Array]': true - , '[object Uint32Array]': true - , '[object Float32Array]': true - , '[object Float64Array]': true + this.name = 'HARError' + this.message = message + this.errors = errors + + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(this, this.constructor) + } else { + this.stack = (new Error(message)).stack + } } -function isTypedArray(arr) { - return ( - isStrictTypedArray(arr) - || isLooseTypedArray(arr) - ) +HARError.prototype = Error.prototype + +module.exports = HARError + + +/***/ }), + +/***/ 75697: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +var Ajv = __nccwpck_require__(64941) +var HARError = __nccwpck_require__(74944) +var schemas = __nccwpck_require__(13679) + +var ajv + +function createAjvInstance () { + var ajv = new Ajv({ + allErrors: true + }) + ajv.addMetaSchema(__nccwpck_require__(96273)) + ajv.addSchema(schemas) + + return ajv } -function isStrictTypedArray(arr) { - return ( - arr instanceof Int8Array - || arr instanceof Int16Array - || arr instanceof Int32Array - || arr instanceof Uint8Array - || arr instanceof Uint8ClampedArray - || arr instanceof Uint16Array - || arr instanceof Uint32Array - || arr instanceof Float32Array - || arr instanceof Float64Array - ) +function validate (name, data) { + data = data || {} + + // validator config + ajv = ajv || createAjvInstance() + + var validate = ajv.getSchema(name + '.json') + + return new Promise(function (resolve, reject) { + var valid = validate(data) + + !valid ? reject(new HARError(validate.errors)) : resolve(data) + }) } -function isLooseTypedArray(arr) { - return names[toString.call(arr)] +exports.afterRequest = function (data) { + return validate('afterRequest', data) } +exports.beforeRequest = function (data) { + return validate('beforeRequest', data) +} -/***/ }), +exports.browser = function (data) { + return validate('browser', data) +} -/***/ 83362: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.cache = function (data) { + return validate('cache', data) +} -var stream = __nccwpck_require__(92413) +exports.content = function (data) { + return validate('content', data) +} +exports.cookie = function (data) { + return validate('cookie', data) +} -function isStream (obj) { - return obj instanceof stream.Stream +exports.creator = function (data) { + return validate('creator', data) } +exports.entry = function (data) { + return validate('entry', data) +} -function isReadable (obj) { - return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object' +exports.har = function (data) { + return validate('har', data) } +exports.header = function (data) { + return validate('header', data) +} -function isWritable (obj) { - return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object' +exports.log = function (data) { + return validate('log', data) } +exports.page = function (data) { + return validate('page', data) +} -function isDuplex (obj) { - return isReadable(obj) && isWritable(obj) +exports.pageTimings = function (data) { + return validate('pageTimings', data) } +exports.postData = function (data) { + return validate('postData', data) +} -module.exports = isStream -module.exports.isReadable = isReadable -module.exports.isWritable = isWritable -module.exports.isDuplex = isDuplex +exports.query = function (data) { + return validate('query', data) +} +exports.request = function (data) { + return validate('request', data) +} -/***/ }), +exports.response = function (data) { + return validate('response', data) +} -/***/ 85587: -/***/ (function(module, exports) { +exports.timings = function (data) { + return validate('timings', data) +} -(function(){ - // Copyright (c) 2005 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. +/***/ }), - // Basic JavaScript BN library - subset useful for RSA encryption. +/***/ 31621: +/***/ ((module) => { - // Bits per digit - var dbits; +"use strict"; - // JavaScript engine analysis - var canary = 0xdeadbeefcafe; - var j_lm = ((canary&0xffffff)==0xefcafe); +module.exports = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; - // (public) Constructor - function BigInteger(a,b,c) { - if(a != null) - if("number" == typeof a) this.fromNumber(a,b,c); - else if(b == null && "string" != typeof a) this.fromString(a,256); - else this.fromString(a,b); - } - // return new, unset BigInteger - function nbi() { return new BigInteger(null); } +/***/ }), - // am: Compute w_j += (x*this_i), propagate carries, - // c is initial carry, returns final carry. - // c < 3*dvalue, x < 2*dvalue, this_i < dvalue - // We need to select the fastest one that works in this environment. +/***/ 15487: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // am1: use a single mult and divide to get the high bits, - // max digit bits should be 26 because - // max internal value = 2*dvalue^2-2*dvalue (< 2^53) - function am1(i,x,w,j,c,n) { - while(--n >= 0) { - var v = x*this[i++]+w[j]+c; - c = Math.floor(v/0x4000000); - w[j++] = v&0x3ffffff; - } - return c; - } - // am2 avoids a big mult-and-extract completely. - // Max digit bits should be <= 30 because we do bitwise ops - // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) - function am2(i,x,w,j,c,n) { - var xl = x&0x7fff, xh = x>>15; - while(--n >= 0) { - var l = this[i]&0x7fff; - var h = this[i++]>>15; - var m = xh*l+h*xl; - l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); - c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); - w[j++] = l&0x3fffffff; - } - return c; - } - // Alternately, set max digit bits to 28 since some - // browsers slow down when dealing with 32-bit numbers. - function am3(i,x,w,j,c,n) { - var xl = x&0x3fff, xh = x>>14; - while(--n >= 0) { - var l = this[i]&0x3fff; - var h = this[i++]>>14; - var m = xh*l+h*xl; - l = xl*l+((m&0x3fff)<<14)+w[j]+c; - c = (l>>28)+(m>>14)+xh*h; - w[j++] = l&0xfffffff; - } - return c; - } - var inBrowser = typeof navigator !== "undefined"; - if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { - BigInteger.prototype.am = am2; - dbits = 30; - } - else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { - BigInteger.prototype.am = am1; - dbits = 26; - } - else { // Mozilla/Netscape seems to prefer am3 - BigInteger.prototype.am = am3; - dbits = 28; - } +"use strict"; - BigInteger.prototype.DB = dbits; - BigInteger.prototype.DM = ((1< { + let encoding = whatwgEncoding.getBOMEncoding(buffer); // see https://github.com/whatwg/html/issues/1910 - // Digit conversions - var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; - var BI_RC = new Array(); - var rr,vv; - rr = "0".charCodeAt(0); - for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; - rr = "a".charCodeAt(0); - for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - rr = "A".charCodeAt(0); - for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + if (encoding === null && transportLayerEncodingLabel !== undefined) { + encoding = whatwgEncoding.labelToName(transportLayerEncodingLabel); + } - function int2char(n) { return BI_RM.charAt(n); } - function intAt(s,i) { - var c = BI_RC[s.charCodeAt(i)]; - return (c==null)?-1:c; - } + if (encoding === null) { + encoding = prescanMetaCharset(buffer); + } - // (protected) copy this to r - function bnpCopyTo(r) { - for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; - r.t = this.t; - r.s = this.s; - } + if (encoding === null) { + encoding = defaultEncoding; + } - // (protected) set from integer value x, -DV <= x < DV - function bnpFromInt(x) { - this.t = 1; - this.s = (x<0)?-1:0; - if(x > 0) this[0] = x; - else if(x < -1) this[0] = x+this.DV; - else this.t = 0; - } + return encoding; +}; - // return bigint initialized to value - function nbv(i) { var r = nbi(); r.fromInt(i); return r; } +// https://html.spec.whatwg.org/multipage/syntax.html#prescan-a-byte-stream-to-determine-its-encoding +function prescanMetaCharset(buffer) { + const l = Math.min(buffer.length, 1024); + for (let i = 0; i < l; i++) { + let c = buffer[i]; + if (c === 0x3C) { + // "<" + const c1 = buffer[i + 1]; + const c2 = buffer[i + 2]; + const c3 = buffer[i + 3]; + const c4 = buffer[i + 4]; + const c5 = buffer[i + 5]; + // !-- (comment start) + if (c1 === 0x21 && c2 === 0x2D && c3 === 0x2D) { + i += 4; + for (; i < l; i++) { + c = buffer[i]; + const cMinus1 = buffer[i - 1]; + const cMinus2 = buffer[i - 2]; + // --> (comment end) + if (c === 0x3E && cMinus1 === 0x2D && cMinus2 === 0x2D) { + break; + } + } + } else if ((c1 === 0x4D || c1 === 0x6D) && + (c2 === 0x45 || c2 === 0x65) && + (c3 === 0x54 || c3 === 0x74) && + (c4 === 0x41 || c4 === 0x61) && + (isSpaceCharacter(c5) || c5 === 0x2F)) { + // "meta" + space or / + i += 6; + const attributeList = new Set(); + let gotPragma = false; + let needPragma = null; + let charset = null; - // (protected) set from string and radix - function bnpFromString(s,b) { - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 256) k = 8; // byte array - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else { this.fromRadix(s,b); return; } - this.t = 0; - this.s = 0; - var i = s.length, mi = false, sh = 0; - while(--i >= 0) { - var x = (k==8)?s[i]&0xff:intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-") mi = true; + let attrRes; + do { + attrRes = getAttribute(buffer, i, l); + if (attrRes.attr && !attributeList.has(attrRes.attr.name)) { + attributeList.add(attrRes.attr.name); + if (attrRes.attr.name === "http-equiv") { + gotPragma = attrRes.attr.value === "content-type"; + } else if (attrRes.attr.name === "content" && !charset) { + charset = extractCharacterEncodingFromMeta(attrRes.attr.value); + if (charset !== null) { + needPragma = true; + } + } else if (attrRes.attr.name === "charset") { + charset = whatwgEncoding.labelToName(attrRes.attr.value); + needPragma = false; + } + } + i = attrRes.i; + } while (attrRes.attr); + + if (needPragma === null) { continue; } - mi = false; - if(sh == 0) - this[this.t++] = x; - else if(sh+k > this.DB) { - this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); + if (needPragma === true && gotPragma === false) { + continue; + } + if (charset === null) { + continue; + } + + if (charset === "UTF-16LE" || charset === "UTF-16BE") { + charset = "UTF-8"; + } + if (charset === "x-user-defined") { + charset = "windows-1252"; + } + + return charset; + } else if ((c1 >= 0x41 && c1 <= 0x5A) || (c1 >= 0x61 && c1 <= 0x7A)) { + // a-z or A-Z + for (i += 2; i < l; i++) { + c = buffer[i]; + // space or > + if (isSpaceCharacter(c) || c === 0x3E) { + break; + } + } + let attrRes; + do { + attrRes = getAttribute(buffer, i, l); + i = attrRes.i; + } while (attrRes.attr); + } else if (c1 === 0x21 || c1 === 0x2F || c1 === 0x3F) { + // ! or / or ? + for (i += 2; i < l; i++) { + c = buffer[i]; + // > + if (c === 0x3E) { + break; + } } - else - this[this.t-1] |= x<= this.DB) sh -= this.DB; - } - if(k == 8 && (s[0]&0x80) != 0) { - this.s = -1; - if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; +// https://html.spec.whatwg.org/multipage/syntax.html#concept-get-attributes-when-sniffing +function getAttribute(buffer, i, l) { + for (; i < l; i++) { + let c = buffer[i]; + // space or / + if (isSpaceCharacter(c) || c === 0x2F) { + continue; } - - // (public) return string representation in given radix - function bnToString(b) { - if(this.s < 0) return "-"+this.negate().toString(b); - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else return this.toRadix(b); - var km = (1< 0) { - if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } - while(i >= 0) { - if(p < k) { - d = (this[i]&((1<>(p+=this.DB-k); + // ">" + if (c === 0x3E) { + break; + } + let name = ""; + let value = ""; + nameLoop:for (; i < l; i++) { + c = buffer[i]; + // "=" + if (c === 0x3D && name !== "") { + i++; + break; + } + // space + if (isSpaceCharacter(c)) { + for (i++; i < l; i++) { + c = buffer[i]; + // space + if (isSpaceCharacter(c)) { + continue; } - else { - d = (this[i]>>(p-=k))&km; - if(p <= 0) { p += this.DB; --i; } + // not "=" + if (c !== 0x3D) { + return { attr: { name, value }, i }; } - if(d > 0) m = true; - if(m) r += int2char(d); + + i++; + break nameLoop; } + break; + } + // / or > + if (c === 0x2F || c === 0x3E) { + return { attr: { name, value }, i }; + } + // A-Z + if (c >= 0x41 && c <= 0x5A) { + name += String.fromCharCode(c + 0x20); // lowercase + } else { + name += String.fromCharCode(c); } - return m?r:"0"; } + c = buffer[i]; + // space + if (isSpaceCharacter(c)) { + for (i++; i < l; i++) { + c = buffer[i]; + // space + if (isSpaceCharacter(c)) { + continue; + } else { + break; + } + } + } + // " or ' + if (c === 0x22 || c === 0x27) { + const quote = c; + for (i++; i < l; i++) { + c = buffer[i]; - // (public) -this - function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } - - // (public) |this| - function bnAbs() { return (this.s<0)?this.negate():this; } + if (c === quote) { + i++; + return { attr: { name, value }, i }; + } - // (public) return + if this > a, - if this < a, 0 if equal - function bnCompareTo(a) { - var r = this.s-a.s; - if(r != 0) return r; - var i = this.t; - r = i-a.t; - if(r != 0) return (this.s<0)?-r:r; - while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; - return 0; + // A-Z + if (c >= 0x41 && c <= 0x5A) { + value += String.fromCharCode(c + 0x20); // lowercase + } else { + value += String.fromCharCode(c); + } + } } - // returns bit length of the integer x - function nbits(x) { - var r = 1, t; - if((t=x>>>16) != 0) { x = t; r += 16; } - if((t=x>>8) != 0) { x = t; r += 8; } - if((t=x>>4) != 0) { x = t; r += 4; } - if((t=x>>2) != 0) { x = t; r += 2; } - if((t=x>>1) != 0) { x = t; r += 1; } - return r; + // > + if (c === 0x3E) { + return { attr: { name, value }, i }; } - // (public) return the number of bits in "this" - function bnBitLength() { - if(this.t <= 0) return 0; - return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); + // A-Z + if (c >= 0x41 && c <= 0x5A) { + value += String.fromCharCode(c + 0x20); // lowercase + } else { + value += String.fromCharCode(c); } - // (protected) r = this << n*DB - function bnpDLShiftTo(n,r) { - var i; - for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; - for(i = n-1; i >= 0; --i) r[i] = 0; - r.t = this.t+n; - r.s = this.s; - } - - // (protected) r = this >> n*DB - function bnpDRShiftTo(n,r) { - for(var i = n; i < this.t; ++i) r[i-n] = this[i]; - r.t = Math.max(this.t-n,0); - r.s = this.s; - } + for (i++; i < l; i++) { + c = buffer[i]; - // (protected) r = this << n - function bnpLShiftTo(n,r) { - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<= 0; --i) { - r[i+ds+1] = (this[i]>>cbs)|c; - c = (this[i]&bm)< + if (isSpaceCharacter(c) || c === 0x3E) { + return { attr: { name, value }, i }; } - for(i = ds-1; i >= 0; --i) r[i] = 0; - r[ds] = c; - r.t = this.t+ds+1; - r.s = this.s; - r.clamp(); - } - // (protected) r = this >> n - function bnpRShiftTo(n,r) { - r.s = this.s; - var ds = Math.floor(n/this.DB); - if(ds >= this.t) { r.t = 0; return; } - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<>bs; - for(var i = ds+1; i < this.t; ++i) { - r[i-ds-1] |= (this[i]&bm)<>bs; + // A-Z + if (c >= 0x41 && c <= 0x5A) { + value += String.fromCharCode(c + 0x20); // lowercase + } else { + value += String.fromCharCode(c); } - if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; - } - if(a.t < this.t) { - c -= a.s; - while(i < this.t) { - c += this[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; - } - else { - c += this.s; - while(i < a.t) { - c -= a[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = (c<0)?-1:0; - if(c < -1) r[i++] = this.DV+c; - else if(c > 0) r[i++] = c; - r.t = i; - r.clamp(); - } +function extractCharacterEncodingFromMeta(string) { + let position = 0; - // (protected) r = this * a, r != this,a (HAC 14.12) - // "this" should be the larger one if appropriate. - function bnpMultiplyTo(a,r) { - var x = this.abs(), y = a.abs(); - var i = x.t; - r.t = i+y.t; - while(--i >= 0) r[i] = 0; - for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); - r.s = 0; - r.clamp(); - if(this.s != a.s) BigInteger.ZERO.subTo(r,r); - } + while (true) { + const indexOfCharset = string.substring(position).search(/charset/i); - // (protected) r = this^2, r != this (HAC 14.16) - function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2*x.t; - while(--i >= 0) r[i] = 0; - for(i = 0; i < x.t-1; ++i) { - var c = x.am(i,x[i],r,2*i,0,1); - if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { - r[i+x.t] -= x.DV; - r[i+x.t+1] = 1; - } - } - if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); - r.s = 0; - r.clamp(); + if (indexOfCharset === -1) { + return null; } + let subPosition = position + indexOfCharset + "charset".length; - // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) - // r != q, this != m. q or r may be null. - function bnpDivRemTo(m,q,r) { - var pm = m.abs(); - if(pm.t <= 0) return; - var pt = this.abs(); - if(pt.t < pm.t) { - if(q != null) q.fromInt(0); - if(r != null) this.copyTo(r); - return; - } - if(r == null) r = nbi(); - var y = nbi(), ts = this.s, ms = m.s; - var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus - if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } - else { pm.copyTo(y); pt.copyTo(r); } - var ys = y.t; - var y0 = y[ys-1]; - if(y0 == 0) return; - var yt = y0*(1<1)?y[ys-2]>>this.F2:0); - var d1 = this.FV/yt, d2 = (1<= 0) { - r[r.t++] = 1; - r.subTo(t,r); - } - BigInteger.ONE.dlShiftTo(ys,t); - t.subTo(y,y); // "negative" y so we can replace sub with am later - while(y.t < ys) y[y.t++] = 0; - while(--j >= 0) { - // Estimate quotient digit - var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); - if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out - y.dlShiftTo(j,t); - r.subTo(t,r); - while(r[i] < --qd) r.subTo(t,r); - } - } - if(q != null) { - r.drShiftTo(ys,q); - if(ts != ms) BigInteger.ZERO.subTo(q,q); - } - r.t = ys; - r.clamp(); - if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder - if(ts < 0) BigInteger.ZERO.subTo(r,r); + while (isSpaceCharacter(string[subPosition].charCodeAt(0))) { + ++subPosition; } - // (public) this mod a - function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a,null,r); - if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); - return r; + if (string[subPosition] !== "=") { + position = subPosition - 1; + continue; } - // Modular reduction using "classic" algorithm - function Classic(m) { this.m = m; } - function cConvert(x) { - if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; + ++subPosition; + + while (isSpaceCharacter(string[subPosition].charCodeAt(0))) { + ++subPosition; } - function cRevert(x) { return x; } - function cReduce(x) { x.divRemTo(this.m,null,x); } - function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } - function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - Classic.prototype.convert = cConvert; - Classic.prototype.revert = cRevert; - Classic.prototype.reduce = cReduce; - Classic.prototype.mulTo = cMulTo; - Classic.prototype.sqrTo = cSqrTo; + position = subPosition; + break; + } - // (protected) return "-1/this % 2^DB"; useful for Mont. reduction - // justification: - // xy == 1 (mod m) - // xy = 1+km - // xy(2-xy) = (1+km)(1-km) - // x[y(2-xy)] = 1-k^2m^2 - // x[y(2-xy)] == 1 (mod m^2) - // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 - // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. - // JS multiply "overflows" differently from C/C++, so care is needed here. - function bnpInvDigit() { - if(this.t < 1) return 0; - var x = this[0]; - if((x&1) == 0) return 0; - var y = x&3; // y == 1/x mod 2^2 - y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 - y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 - y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y>0)?this.DV-y:-y; - } + if (string[position] === "\"" || string[position] === "'") { + const nextIndex = string.indexOf(string[position], position + 1); - // Montgomery reduction - function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp&0x7fff; - this.mph = this.mp>>15; - this.um = (1<<(m.DB-15))-1; - this.mt2 = 2*m.t; + if (nextIndex !== -1) { + return whatwgEncoding.labelToName(string.substring(position + 1, nextIndex)); } - // xR mod m - function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t,r); - r.divRemTo(this.m,null,r); - if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); - return r; - } + // It is an unmatched quotation mark + return null; + } - // x/R mod m - function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } + if (string.length === position + 1) { + return null; + } - // x = x/R mod m (HAC 14.32) - function montReduce(x) { - while(x.t <= this.mt2) // pad x so am has enough room later - x[x.t++] = 0; - for(var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i]&0x7fff; - var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; - // use am to combine the multiply-shift-add into one call - j = i+this.m.t; - x[j] += this.m.am(0,u0,x,i,0,this.m.t); - // propagate carry - while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } - } - x.clamp(); - x.drShiftTo(this.m.t,x); - if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); - } + const indexOfASCIIWhitespaceOrSemicolon = string.substring(position + 1).search(/\x09|\x0A|\x0C|\x0D|\x20|;/); + const end = indexOfASCIIWhitespaceOrSemicolon === -1 ? + string.length : + position + indexOfASCIIWhitespaceOrSemicolon + 1; - // r = "x^2/R mod m"; x != r - function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + return whatwgEncoding.labelToName(string.substring(position, end)); +} - // r = "xy/R mod m"; x,y != r - function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } +function isSpaceCharacter(c) { + return c === 0x09 || c === 0x0A || c === 0x0C || c === 0x0D || c === 0x20; +} - Montgomery.prototype.convert = montConvert; - Montgomery.prototype.revert = montRevert; - Montgomery.prototype.reduce = montReduce; - Montgomery.prototype.mulTo = montMulTo; - Montgomery.prototype.sqrTo = montSqrTo; - // (protected) true iff this is even - function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } +/***/ }), - // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) - function bnpExp(e,z) { - if(e > 0xffffffff || e < 1) return BigInteger.ONE; - var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; - g.copyTo(r); - while(--i >= 0) { - z.sqrTo(r,r2); - if((e&(1< 0) z.mulTo(r2,g,r); - else { var t = r; r = r2; r2 = t; } - } - return z.revert(r); - } +/***/ 42479: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // (public) this^e % m, 0 <= e < 2^32 - function bnModPowInt(e,m) { - var z; - if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); - return this.exp(e,z); - } +// Copyright 2015 Joyent, Inc. - // protected - BigInteger.prototype.copyTo = bnpCopyTo; - BigInteger.prototype.fromInt = bnpFromInt; - BigInteger.prototype.fromString = bnpFromString; - BigInteger.prototype.clamp = bnpClamp; - BigInteger.prototype.dlShiftTo = bnpDLShiftTo; - BigInteger.prototype.drShiftTo = bnpDRShiftTo; - BigInteger.prototype.lShiftTo = bnpLShiftTo; - BigInteger.prototype.rShiftTo = bnpRShiftTo; - BigInteger.prototype.subTo = bnpSubTo; - BigInteger.prototype.multiplyTo = bnpMultiplyTo; - BigInteger.prototype.squareTo = bnpSquareTo; - BigInteger.prototype.divRemTo = bnpDivRemTo; - BigInteger.prototype.invDigit = bnpInvDigit; - BigInteger.prototype.isEven = bnpIsEven; - BigInteger.prototype.exp = bnpExp; +var parser = __nccwpck_require__(95086); +var signer = __nccwpck_require__(38143); +var verify = __nccwpck_require__(51227); +var utils = __nccwpck_require__(65689); - // public - BigInteger.prototype.toString = bnToString; - BigInteger.prototype.negate = bnNegate; - BigInteger.prototype.abs = bnAbs; - BigInteger.prototype.compareTo = bnCompareTo; - BigInteger.prototype.bitLength = bnBitLength; - BigInteger.prototype.mod = bnMod; - BigInteger.prototype.modPowInt = bnModPowInt; - // "constants" - BigInteger.ZERO = nbv(0); - BigInteger.ONE = nbv(1); - // Copyright (c) 2005-2009 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. +///--- API - // Extended JavaScript BN functions, required for RSA private ops. +module.exports = { - // Version 1.1: new BigInteger("0", 10) returns "proper" zero - // Version 1.2: square() API, isProbablePrime fix + parse: parser.parseRequest, + parseRequest: parser.parseRequest, - // (public) - function bnClone() { var r = nbi(); this.copyTo(r); return r; } + sign: signer.signRequest, + signRequest: signer.signRequest, + createSigner: signer.createSigner, + isSigner: signer.isSigner, - // (public) return value as integer - function bnIntValue() { - if(this.s < 0) { - if(this.t == 1) return this[0]-this.DV; - else if(this.t == 0) return -1; - } - else if(this.t == 1) return this[0]; - else if(this.t == 0) return 0; - // assumes 16 < DB < 32 - return ((this[1]&((1<<(32-this.DB))-1))<>24; } + verify: verify.verifySignature, + verifySignature: verify.verifySignature, + verifyHMAC: verify.verifyHMAC +}; - // (public) return value as short (assumes DB>=16) - function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } - // (protected) return x s.t. r^x < DV - function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } +/***/ }), - // (public) 0 if this == 0, 1 if this > 0 - function bnSigNum() { - if(this.s < 0) return -1; - else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; - else return 1; - } +/***/ 95086: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // (protected) convert to radix string - function bnpToRadix(b) { - if(b == null) b = 10; - if(this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b,cs); - var d = nbv(a), y = nbi(), z = nbi(), r = ""; - this.divRemTo(d,y,z); - while(y.signum() > 0) { - r = (a+z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d,y,z); - } - return z.intValue().toString(b) + r; - } +// Copyright 2012 Joyent, Inc. All rights reserved. - // (protected) convert from radix string - function bnpFromRadix(s,b) { - this.fromInt(0); - if(b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b,cs), mi = false, j = 0, w = 0; - for(var i = 0; i < s.length; ++i) { - var x = intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b*w+x; - if(++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w,0); - j = 0; - w = 0; - } - } - if(j > 0) { - this.dMultiply(Math.pow(b,j)); - this.dAddOffset(w,0); - } - if(mi) BigInteger.ZERO.subTo(this,this); - } +var assert = __nccwpck_require__(66631); +var util = __nccwpck_require__(73837); +var utils = __nccwpck_require__(65689); - // (protected) alternate constructor - function bnpFromNumber(a,b,c) { - if("number" == typeof b) { - // new BigInteger(int,int,RNG) - if(a < 2) this.fromInt(1); - else { - this.fromNumber(a,c); - if(!this.testBit(a-1)) // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); - if(this.isEven()) this.dAddOffset(1,0); // force odd - while(!this.isProbablePrime(b)) { - this.dAddOffset(2,0); - if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); - } - } - } - else { - // new BigInteger(int,RNG) - var x = new Array(), t = a&7; - x.length = (a>>3)+1; - b.nextBytes(x); - if(t > 0) x[0] &= ((1< 0) { - if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) - r[k++] = d|(this.s<<(this.DB-p)); - while(i >= 0) { - if(p < 8) { - d = (this[i]&((1<>(p+=this.DB-8); - } - else { - d = (this[i]>>(p-=8))&0xff; - if(p <= 0) { p += this.DB; --i; } - } - if((d&0x80) != 0) d |= -256; - if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; - if(k > 0 || d != this.s) r[k++] = d; - } - } - return r; - } - function bnEquals(a) { return(this.compareTo(a)==0); } - function bnMin(a) { return(this.compareTo(a)<0)?this:a; } - function bnMax(a) { return(this.compareTo(a)>0)?this:a; } +///--- Globals - // (protected) r = this op a (bitwise) - function bnpBitwiseTo(a,op,r) { - var i, f, m = Math.min(a.t,this.t); - for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); - if(a.t < this.t) { - f = a.s&this.DM; - for(i = m; i < this.t; ++i) r[i] = op(this[i],f); - r.t = this.t; - } - else { - f = this.s&this.DM; - for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); - r.t = a.t; - } - r.s = op(this.s,a.s); - r.clamp(); - } +var HASH_ALGOS = utils.HASH_ALGOS; +var PK_ALGOS = utils.PK_ALGOS; +var HttpSignatureError = utils.HttpSignatureError; +var InvalidAlgorithmError = utils.InvalidAlgorithmError; +var validateAlgorithm = utils.validateAlgorithm; - // (public) this & a - function op_and(x,y) { return x&y; } - function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } +var State = { + New: 0, + Params: 1 +}; - // (public) this | a - function op_or(x,y) { return x|y; } - function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } +var ParamsState = { + Name: 0, + Quote: 1, + Value: 2, + Comma: 3 +}; - // (public) this ^ a - function op_xor(x,y) { return x^y; } - function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } - // (public) this & ~a - function op_andnot(x,y) { return x&~y; } - function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } +///--- Specific Errors - // (public) ~this - function bnNot() { - var r = nbi(); - for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; - r.t = this.t; - r.s = ~this.s; - return r; - } - // (public) this << n - function bnShiftLeft(n) { - var r = nbi(); - if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); - return r; - } +function ExpiredRequestError(message) { + HttpSignatureError.call(this, message, ExpiredRequestError); +} +util.inherits(ExpiredRequestError, HttpSignatureError); - // (public) this >> n - function bnShiftRight(n) { - var r = nbi(); - if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); - return r; - } - // return index of lowest 1-bit in x, x < 2^31 - function lbit(x) { - if(x == 0) return -1; - var r = 0; - if((x&0xffff) == 0) { x >>= 16; r += 16; } - if((x&0xff) == 0) { x >>= 8; r += 8; } - if((x&0xf) == 0) { x >>= 4; r += 4; } - if((x&3) == 0) { x >>= 2; r += 2; } - if((x&1) == 0) ++r; - return r; - } +function InvalidHeaderError(message) { + HttpSignatureError.call(this, message, InvalidHeaderError); +} +util.inherits(InvalidHeaderError, HttpSignatureError); - // (public) returns index of lowest 1-bit (or -1 if none) - function bnGetLowestSetBit() { - for(var i = 0; i < this.t; ++i) - if(this[i] != 0) return i*this.DB+lbit(this[i]); - if(this.s < 0) return this.t*this.DB; - return -1; - } - // return number of 1 bits in x - function cbit(x) { - var r = 0; - while(x != 0) { x &= x-1; ++r; } - return r; - } +function InvalidParamsError(message) { + HttpSignatureError.call(this, message, InvalidParamsError); +} +util.inherits(InvalidParamsError, HttpSignatureError); - // (public) return number of set bits - function bnBitCount() { - var r = 0, x = this.s&this.DM; - for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); - return r; - } - // (public) true iff nth bit is set - function bnTestBit(n) { - var j = Math.floor(n/this.DB); - if(j >= this.t) return(this.s!=0); - return((this[j]&(1<<(n%this.DB)))!=0); - } +function MissingHeaderError(message) { + HttpSignatureError.call(this, message, MissingHeaderError); +} +util.inherits(MissingHeaderError, HttpSignatureError); - // (protected) this op (1<>= this.DB; - } - if(a.t < this.t) { - c += a.s; - while(i < this.t) { - c += this[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; - } - else { - c += this.s; - while(i < a.t) { - c += a[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = (c<0)?-1:0; - if(c > 0) r[i++] = c; - else if(c < -1) r[i++] = this.DV+c; - r.t = i; - r.clamp(); + var authzHeaderName = options.authorizationHeaderName || 'authorization'; + + if (!request.headers[authzHeaderName]) { + throw new MissingHeaderError('no ' + authzHeaderName + ' header ' + + 'present in the request'); } - // (public) this + a - function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } + options.clockSkew = options.clockSkew || 300; - // (public) this - a - function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } - // (public) this * a - function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } + var i = 0; + var state = State.New; + var substate = ParamsState.Name; + var tmpName = ''; + var tmpValue = ''; - // (public) this^2 - function bnSquare() { var r = nbi(); this.squareTo(r); return r; } + var parsed = { + scheme: '', + params: {}, + signingString: '' + }; - // (public) this / a - function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } + var authz = request.headers[authzHeaderName]; + for (i = 0; i < authz.length; i++) { + var c = authz.charAt(i); - // (public) this % a - function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } + switch (Number(state)) { - // (public) [this/a,this%a] - function bnDivideAndRemainder(a) { - var q = nbi(), r = nbi(); - this.divRemTo(a,q,r); - return new Array(q,r); - } + case State.New: + if (c !== ' ') parsed.scheme += c; + else state = State.Params; + break; - // (protected) this *= n, this >= 0, 1 < n < DV - function bnpDMultiply(n) { - this[this.t] = this.am(0,n-1,this,0,0,this.t); - ++this.t; - this.clamp(); - } + case State.Params: + switch (Number(substate)) { - // (protected) this += n << w words, this >= 0 - function bnpDAddOffset(n,w) { - if(n == 0) return; - while(this.t <= w) this[this.t++] = 0; - this[w] += n; - while(this[w] >= this.DV) { - this[w] -= this.DV; - if(++w >= this.t) this[this.t++] = 0; - ++this[w]; - } - } + case ParamsState.Name: + var code = c.charCodeAt(0); + // restricted name of A-Z / a-z + if ((code >= 0x41 && code <= 0x5a) || // A-Z + (code >= 0x61 && code <= 0x7a)) { // a-z + tmpName += c; + } else if (c === '=') { + if (tmpName.length === 0) + throw new InvalidHeaderError('bad param format'); + substate = ParamsState.Quote; + } else { + throw new InvalidHeaderError('bad param format'); + } + break; - // A "null" reducer - function NullExp() {} - function nNop(x) { return x; } - function nMulTo(x,y,r) { x.multiplyTo(y,r); } - function nSqrTo(x,r) { x.squareTo(r); } + case ParamsState.Quote: + if (c === '"') { + tmpValue = ''; + substate = ParamsState.Value; + } else { + throw new InvalidHeaderError('bad param format'); + } + break; - NullExp.prototype.convert = nNop; - NullExp.prototype.revert = nNop; - NullExp.prototype.mulTo = nMulTo; - NullExp.prototype.sqrTo = nSqrTo; + case ParamsState.Value: + if (c === '"') { + parsed.params[tmpName] = tmpValue; + substate = ParamsState.Comma; + } else { + tmpValue += c; + } + break; - // (public) this^e - function bnPow(e) { return this.exp(e,new NullExp()); } + case ParamsState.Comma: + if (c === ',') { + tmpName = ''; + substate = ParamsState.Name; + } else { + throw new InvalidHeaderError('bad param format'); + } + break; - // (protected) r = lower n words of "this * a", a.t <= n - // "this" should be the larger one if appropriate. - function bnpMultiplyLowerTo(a,n,r) { - var i = Math.min(this.t+a.t,n); - r.s = 0; // assumes a,this >= 0 - r.t = i; - while(i > 0) r[--i] = 0; - var j; - for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); - for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); - r.clamp(); - } + default: + throw new Error('Invalid substate'); + } + break; - // (protected) r = "this * a" without lower n words, n > 0 - // "this" should be the larger one if appropriate. - function bnpMultiplyUpperTo(a,n,r) { - --n; - var i = r.t = this.t+a.t-n; - r.s = 0; // assumes a,this >= 0 - while(--i >= 0) r[i] = 0; - for(i = Math.max(n-this.t,0); i < a.t; ++i) - r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); - r.clamp(); - r.drShiftTo(1,r); - } + default: + throw new Error('Invalid substate'); + } - // Barrett modular reduction - function Barrett(m) { - // setup Barrett - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2*m.t,this.r2); - this.mu = this.r2.divide(m); - this.m = m; } - function barrettConvert(x) { - if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); - else if(x.compareTo(this.m) < 0) return x; - else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } + if (!parsed.params.headers || parsed.params.headers === '') { + if (request.headers['x-date']) { + parsed.params.headers = ['x-date']; + } else { + parsed.params.headers = ['date']; + } + } else { + parsed.params.headers = parsed.params.headers.split(' '); } - function barrettRevert(x) { return x; } - - // x = x mod m (HAC 14.42) - function barrettReduce(x) { - x.drShiftTo(this.m.t-1,this.r2); - if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } - this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); - this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); - while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); - x.subTo(this.r2,x); - while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); - } + // Minimally validate the parsed object + if (!parsed.scheme || parsed.scheme !== 'Signature') + throw new InvalidHeaderError('scheme was not "Signature"'); - // r = x^2 mod m; x != r - function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + if (!parsed.params.keyId) + throw new InvalidHeaderError('keyId was not specified'); - // r = x*y mod m; x,y != r - function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + if (!parsed.params.algorithm) + throw new InvalidHeaderError('algorithm was not specified'); - Barrett.prototype.convert = barrettConvert; - Barrett.prototype.revert = barrettRevert; - Barrett.prototype.reduce = barrettReduce; - Barrett.prototype.mulTo = barrettMulTo; - Barrett.prototype.sqrTo = barrettSqrTo; + if (!parsed.params.signature) + throw new InvalidHeaderError('signature was not specified'); - // (public) this^e % m (HAC 14.85) - function bnModPow(e,m) { - var i = e.bitLength(), k, r = nbv(1), z; - if(i <= 0) return r; - else if(i < 18) k = 1; - else if(i < 48) k = 3; - else if(i < 144) k = 4; - else if(i < 768) k = 5; - else k = 6; - if(i < 8) - z = new Classic(m); - else if(m.isEven()) - z = new Barrett(m); + // Check the algorithm against the official list + parsed.params.algorithm = parsed.params.algorithm.toLowerCase(); + try { + validateAlgorithm(parsed.params.algorithm); + } catch (e) { + if (e instanceof InvalidAlgorithmError) + throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' + + 'supported')); else - z = new Montgomery(m); + throw (e); + } - // precomputation - var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { - var g2 = nbi(); - z.sqrTo(g[1],g2); - while(n <= km) { - g[n] = nbi(); - z.mulTo(g2,g[n-2],g[n]); - n += 2; + // Build the signingString + for (i = 0; i < parsed.params.headers.length; i++) { + var h = parsed.params.headers[i].toLowerCase(); + parsed.params.headers[i] = h; + + if (h === 'request-line') { + if (!options.strict) { + /* + * We allow headers from the older spec drafts if strict parsing isn't + * specified in options. + */ + parsed.signingString += + request.method + ' ' + request.url + ' HTTP/' + request.httpVersion; + } else { + /* Strict parsing doesn't allow older draft headers. */ + throw (new StrictParsingError('request-line is not a valid header ' + + 'with strict parsing enabled.')); } + } else if (h === '(request-target)') { + parsed.signingString += + '(request-target): ' + request.method.toLowerCase() + ' ' + + request.url; + } else { + var value = request.headers[h]; + if (value === undefined) + throw new MissingHeaderError(h + ' was not in the request'); + parsed.signingString += h + ': ' + value; } - var j = e.t-1, w, is1 = true, r2 = nbi(), t; - i = nbits(e[j])-1; - while(j >= 0) { - if(i >= k1) w = (e[j]>>(i-k1))&km; - else { - w = (e[j]&((1<<(i+1))-1))<<(k1-i); - if(j > 0) w |= e[j-1]>>(this.DB+i-k1); - } + if ((i + 1) < parsed.params.headers.length) + parsed.signingString += '\n'; + } - n = k; - while((w&1) == 0) { w >>= 1; --n; } - if((i -= n) < 0) { i += this.DB; --j; } - if(is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r); - is1 = false; - } - else { - while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } - if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } - z.mulTo(r2,g[w],r); + // Check against the constraints + var date; + if (request.headers.date || request.headers['x-date']) { + if (request.headers['x-date']) { + date = new Date(request.headers['x-date']); + } else { + date = new Date(request.headers.date); } + var now = new Date(); + var skew = Math.abs(now.getTime() - date.getTime()); - while(j >= 0 && (e[j]&(1< options.clockSkew * 1000) { + throw new ExpiredRequestError('clock skew of ' + + (skew / 1000) + + 's was greater than ' + + options.clockSkew + 's'); } - return z.revert(r); } - // (public) gcd(this,a) (HAC 14.54) - function bnGCD(a) { - var x = (this.s<0)?this.negate():this.clone(); - var y = (a.s<0)?a.negate():a.clone(); - if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } - var i = x.getLowestSetBit(), g = y.getLowestSetBit(); - if(g < 0) return x; - if(i < g) g = i; - if(g > 0) { - x.rShiftTo(g,x); - y.rShiftTo(g,y); - } - while(x.signum() > 0) { - if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); - if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); - if(x.compareTo(y) >= 0) { - x.subTo(y,x); - x.rShiftTo(1,x); - } - else { - y.subTo(x,y); - y.rShiftTo(1,y); - } - } - if(g > 0) y.lShiftTo(g,y); - return y; - } - - // (protected) this % n, n < 2^26 - function bnpModInt(n) { - if(n <= 0) return 0; - var d = this.DV%n, r = (this.s<0)?n-1:0; - if(this.t > 0) - if(d == 0) r = this[0]%n; - else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; - return r; - } - - // (public) 1/this % m (HAC 14.61) - function bnModInverse(m) { - var ac = m.isEven(); - if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), v = this.clone(); - var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); - while(u.signum() != 0) { - while(u.isEven()) { - u.rShiftTo(1,u); - if(ac) { - if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } - a.rShiftTo(1,a); - } - else if(!b.isEven()) b.subTo(m,b); - b.rShiftTo(1,b); - } - while(v.isEven()) { - v.rShiftTo(1,v); - if(ac) { - if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } - c.rShiftTo(1,c); - } - else if(!d.isEven()) d.subTo(m,d); - d.rShiftTo(1,d); - } - if(u.compareTo(v) >= 0) { - u.subTo(v,u); - if(ac) a.subTo(c,a); - b.subTo(d,b); - } - else { - v.subTo(u,v); - if(ac) c.subTo(a,c); - d.subTo(b,d); - } - } - if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; - if(d.compareTo(m) >= 0) return d.subtract(m); - if(d.signum() < 0) d.addTo(m,d); else return d; - if(d.signum() < 0) return d.add(m); else return d; - } - - var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; - var lplim = (1<<26)/lowprimes[lowprimes.length-1]; + options.headers.forEach(function (hdr) { + // Remember that we already checked any headers in the params + // were in the request, so if this passes we're good. + if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0) + throw new MissingHeaderError(hdr + ' was not a signed header'); + }); - // (public) test primality with certainty >= 1-.5^t - function bnIsProbablePrime(t) { - var i, x = this.abs(); - if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { - for(i = 0; i < lowprimes.length; ++i) - if(x[0] == lowprimes[i]) return true; - return false; - } - if(x.isEven()) return false; - i = 1; - while(i < lowprimes.length) { - var m = lowprimes[i], j = i+1; - while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while(i < j) if(m%lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); + if (options.algorithms) { + if (options.algorithms.indexOf(parsed.params.algorithm) === -1) + throw new InvalidParamsError(parsed.params.algorithm + + ' is not a supported algorithm'); } - // (protected) true if probably prime (HAC 4.24, Miller-Rabin) - function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); - if(k <= 0) return false; - var r = n1.shiftRight(k); - t = (t+1)>>1; - if(t > lowprimes.length) t = lowprimes.length; - var a = nbi(); - for(var i = 0; i < t; ++i) { - //Pick bases at random, instead of starting at 2 - a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); - var y = a.modPow(r,this); - if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while(j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2,this); - if(y.compareTo(BigInteger.ONE) == 0) return false; - } - if(y.compareTo(n1) != 0) return false; - } - } - return true; - } + parsed.algorithm = parsed.params.algorithm.toUpperCase(); + parsed.keyId = parsed.params.keyId; + return parsed; + } - // protected - BigInteger.prototype.chunkSize = bnpChunkSize; - BigInteger.prototype.toRadix = bnpToRadix; - BigInteger.prototype.fromRadix = bnpFromRadix; - BigInteger.prototype.fromNumber = bnpFromNumber; - BigInteger.prototype.bitwiseTo = bnpBitwiseTo; - BigInteger.prototype.changeBit = bnpChangeBit; - BigInteger.prototype.addTo = bnpAddTo; - BigInteger.prototype.dMultiply = bnpDMultiply; - BigInteger.prototype.dAddOffset = bnpDAddOffset; - BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; - BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; - BigInteger.prototype.modInt = bnpModInt; - BigInteger.prototype.millerRabin = bnpMillerRabin; +}; - // public - BigInteger.prototype.clone = bnClone; - BigInteger.prototype.intValue = bnIntValue; - BigInteger.prototype.byteValue = bnByteValue; - BigInteger.prototype.shortValue = bnShortValue; - BigInteger.prototype.signum = bnSigNum; - BigInteger.prototype.toByteArray = bnToByteArray; - BigInteger.prototype.equals = bnEquals; - BigInteger.prototype.min = bnMin; - BigInteger.prototype.max = bnMax; - BigInteger.prototype.and = bnAnd; - BigInteger.prototype.or = bnOr; - BigInteger.prototype.xor = bnXor; - BigInteger.prototype.andNot = bnAndNot; - BigInteger.prototype.not = bnNot; - BigInteger.prototype.shiftLeft = bnShiftLeft; - BigInteger.prototype.shiftRight = bnShiftRight; - BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; - BigInteger.prototype.bitCount = bnBitCount; - BigInteger.prototype.testBit = bnTestBit; - BigInteger.prototype.setBit = bnSetBit; - BigInteger.prototype.clearBit = bnClearBit; - BigInteger.prototype.flipBit = bnFlipBit; - BigInteger.prototype.add = bnAdd; - BigInteger.prototype.subtract = bnSubtract; - BigInteger.prototype.multiply = bnMultiply; - BigInteger.prototype.divide = bnDivide; - BigInteger.prototype.remainder = bnRemainder; - BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; - BigInteger.prototype.modPow = bnModPow; - BigInteger.prototype.modInverse = bnModInverse; - BigInteger.prototype.pow = bnPow; - BigInteger.prototype.gcd = bnGCD; - BigInteger.prototype.isProbablePrime = bnIsProbablePrime; - // JSBN-specific extension - BigInteger.prototype.square = bnSquare; +/***/ }), - // Expose the Barrett function - BigInteger.prototype.Barrett = Barrett +/***/ 38143: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // BigInteger interfaces not implemented in jsbn: +// Copyright 2012 Joyent, Inc. All rights reserved. - // BigInteger(int signum, byte[] magnitude) - // double doubleValue() - // float floatValue() - // int hashCode() - // long longValue() - // static BigInteger valueOf(long val) +var assert = __nccwpck_require__(66631); +var crypto = __nccwpck_require__(6113); +var http = __nccwpck_require__(13685); +var util = __nccwpck_require__(73837); +var sshpk = __nccwpck_require__(87022); +var jsprim = __nccwpck_require__(6287); +var utils = __nccwpck_require__(65689); - // Random number generator - requires a PRNG backend, e.g. prng4.js +var sprintf = (__nccwpck_require__(73837).format); - // For best results, put code like - // - // in your main HTML document. +var HASH_ALGOS = utils.HASH_ALGOS; +var PK_ALGOS = utils.PK_ALGOS; +var InvalidAlgorithmError = utils.InvalidAlgorithmError; +var HttpSignatureError = utils.HttpSignatureError; +var validateAlgorithm = utils.validateAlgorithm; - var rng_state; - var rng_pool; - var rng_pptr; +///--- Globals - // Mix in a 32-bit integer into the pool - function rng_seed_int(x) { - rng_pool[rng_pptr++] ^= x & 255; - rng_pool[rng_pptr++] ^= (x >> 8) & 255; - rng_pool[rng_pptr++] ^= (x >> 16) & 255; - rng_pool[rng_pptr++] ^= (x >> 24) & 255; - if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; - } +var AUTHZ_FMT = + 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"'; - // Mix in the current time (w/milliseconds) into the pool - function rng_seed_time() { - rng_seed_int(new Date().getTime()); - } +///--- Specific Errors - // Initialize the pool with junk if needed. - if(rng_pool == null) { - rng_pool = new Array(); - rng_pptr = 0; - var t; - if(typeof window !== "undefined" && window.crypto) { - if (window.crypto.getRandomValues) { - // Use webcrypto if available - var ua = new Uint8Array(32); - window.crypto.getRandomValues(ua); - for(t = 0; t < 32; ++t) - rng_pool[rng_pptr++] = ua[t]; - } - else if(navigator.appName == "Netscape" && navigator.appVersion < "5") { - // Extract entropy (256 bits) from NS4 RNG if available - var z = window.crypto.random(32); - for(t = 0; t < z.length; ++t) - rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; - } - } - while(rng_pptr < rng_psize) { // extract some randomness from Math.random() - t = Math.floor(65536 * Math.random()); - rng_pool[rng_pptr++] = t >>> 8; - rng_pool[rng_pptr++] = t & 255; - } - rng_pptr = 0; - rng_seed_time(); - //rng_seed_int(window.screenX); - //rng_seed_int(window.screenY); - } +function MissingHeaderError(message) { + HttpSignatureError.call(this, message, MissingHeaderError); +} +util.inherits(MissingHeaderError, HttpSignatureError); - function rng_get_byte() { - if(rng_state == null) { - rng_seed_time(); - rng_state = prng_newstate(); - rng_state.init(rng_pool); - for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) - rng_pool[rng_pptr] = 0; - rng_pptr = 0; - //rng_pool = null; - } - // TODO: allow reseeding after first request - return rng_state.next(); - } +function StrictParsingError(message) { + HttpSignatureError.call(this, message, StrictParsingError); +} +util.inherits(StrictParsingError, HttpSignatureError); - function rng_get_bytes(ba) { - var i; - for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); - } +/* See createSigner() */ +function RequestSigner(options) { + assert.object(options, 'options'); - function SecureRandom() {} + var alg = []; + if (options.algorithm !== undefined) { + assert.string(options.algorithm, 'options.algorithm'); + alg = validateAlgorithm(options.algorithm); + } + this.rs_alg = alg; - SecureRandom.prototype.nextBytes = rng_get_bytes; + /* + * RequestSigners come in two varieties: ones with an rs_signFunc, and ones + * with an rs_signer. + * + * rs_signFunc-based RequestSigners have to build up their entire signing + * string within the rs_lines array and give it to rs_signFunc as a single + * concat'd blob. rs_signer-based RequestSigners can add a line at a time to + * their signing state by using rs_signer.update(), thus only needing to + * buffer the hash function state and one line at a time. + */ + if (options.sign !== undefined) { + assert.func(options.sign, 'options.sign'); + this.rs_signFunc = options.sign; - // prng4.js - uses Arcfour as a PRNG + } else if (alg[0] === 'hmac' && options.key !== undefined) { + assert.string(options.keyId, 'options.keyId'); + this.rs_keyId = options.keyId; - function Arcfour() { - this.i = 0; - this.j = 0; - this.S = new Array(); - } + if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) + throw (new TypeError('options.key for HMAC must be a string or Buffer')); - // Initialize arcfour context from key, an array of ints, each from [0..255] - function ARC4init(key) { - var i, j, t; - for(i = 0; i < 256; ++i) - this.S[i] = i; - j = 0; - for(i = 0; i < 256; ++i) { - j = (j + this.S[i] + key[i % key.length]) & 255; - t = this.S[i]; - this.S[i] = this.S[j]; - this.S[j] = t; - } - this.i = 0; - this.j = 0; - } + /* + * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their + * data in chunks rather than requiring it all to be given in one go + * at the end, so they are more similar to signers than signFuncs. + */ + this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key); + this.rs_signer.sign = function () { + var digest = this.digest('base64'); + return ({ + hashAlgorithm: alg[1], + toString: function () { return (digest); } + }); + }; - function ARC4next() { - var t; - this.i = (this.i + 1) & 255; - this.j = (this.j + this.S[this.i]) & 255; - t = this.S[this.i]; - this.S[this.i] = this.S[this.j]; - this.S[this.j] = t; - return this.S[(t + this.S[this.i]) & 255]; - } + } else if (options.key !== undefined) { + var key = options.key; + if (typeof (key) === 'string' || Buffer.isBuffer(key)) + key = sshpk.parsePrivateKey(key); - Arcfour.prototype.init = ARC4init; - Arcfour.prototype.next = ARC4next; + assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), + 'options.key must be a sshpk.PrivateKey'); + this.rs_key = key; - // Plug in your RNG constructor here - function prng_newstate() { - return new Arcfour(); - } + assert.string(options.keyId, 'options.keyId'); + this.rs_keyId = options.keyId; - // Pool size must be a multiple of 4 and greater than 32. - // An array of bytes the size of the pool will be passed to init() - var rng_psize = 256; + if (!PK_ALGOS[key.type]) { + throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + + 'keys are not supported')); + } - BigInteger.SecureRandom = SecureRandom; - BigInteger.BigInteger = BigInteger; - if (true) { - exports = module.exports = BigInteger; - } else {} + if (alg[0] !== undefined && key.type !== alg[0]) { + throw (new InvalidAlgorithmError('options.key must be a ' + + alg[0].toUpperCase() + ' key, was given a ' + + key.type.toUpperCase() + ' key instead')); + } -}).call(this); + this.rs_signer = key.createSign(alg[1]); + } else { + throw (new TypeError('options.sign (func) or options.key is required')); + } -/***/ }), + this.rs_headers = []; + this.rs_lines = []; +} -/***/ 46123: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Adds a header to be signed, with its value, into this signer. + * + * @param {String} header + * @param {String} value + * @return {String} value written + */ +RequestSigner.prototype.writeHeader = function (header, value) { + assert.string(header, 'header'); + header = header.toLowerCase(); + assert.string(value, 'value'); -"use strict"; + this.rs_headers.push(header); -const path = __nccwpck_require__(85622); -const fs = __nccwpck_require__(35747).promises; -const vm = __nccwpck_require__(92184); -const toughCookie = __nccwpck_require__(47372); -const sniffHTMLEncoding = __nccwpck_require__(15487); -const whatwgURL = __nccwpck_require__(66365); -const whatwgEncoding = __nccwpck_require__(49967); -const { URL } = __nccwpck_require__(66365); -const MIMEType = __nccwpck_require__(59488); -const idlUtils = __nccwpck_require__(34908); -const VirtualConsole = __nccwpck_require__(57704); -const { createWindow } = __nccwpck_require__(55802); -const { parseIntoDocument } = __nccwpck_require__(35373); -const { fragmentSerialization } = __nccwpck_require__(33740); -const ResourceLoader = __nccwpck_require__(90007); -const NoOpResourceLoader = __nccwpck_require__(5383); + if (this.rs_signFunc) { + this.rs_lines.push(header + ': ' + value); -class CookieJar extends toughCookie.CookieJar { - constructor(store, options) { - // jsdom cookie jars must be loose by default - super(store, { looseMode: true, ...options }); + } else { + var line = header + ': ' + value; + if (this.rs_headers.length > 0) + line = '\n' + line; + this.rs_signer.update(line); } -} -const window = Symbol("window"); -let sharedFragmentDocument = null; - -class JSDOM { - constructor(input = "", options = {}) { - const mimeType = new MIMEType(options.contentType === undefined ? "text/html" : options.contentType); - const { html, encoding } = normalizeHTML(input, mimeType); + return (value); +}; - options = transformOptions(options, encoding, mimeType); +/** + * Adds a default Date header, returning its value. + * + * @return {String} + */ +RequestSigner.prototype.writeDateHeader = function () { + return (this.writeHeader('date', jsprim.rfc1123(new Date()))); +}; - this[window] = createWindow(options.windowOptions); +/** + * Adds the request target line to be signed. + * + * @param {String} method, HTTP method (e.g. 'get', 'post', 'put') + * @param {String} path + */ +RequestSigner.prototype.writeTarget = function (method, path) { + assert.string(method, 'method'); + assert.string(path, 'path'); + method = method.toLowerCase(); + this.writeHeader('(request-target)', method + ' ' + path); +}; - const documentImpl = idlUtils.implForWrapper(this[window]._document); +/** + * Calculate the value for the Authorization header on this request + * asynchronously. + * + * @param {Func} callback (err, authz) + */ +RequestSigner.prototype.sign = function (cb) { + assert.func(cb, 'callback'); - options.beforeParse(this[window]._globalProxy); + if (this.rs_headers.length < 1) + throw (new Error('At least one header must be signed')); - parseIntoDocument(html, documentImpl); + var alg, authz; + if (this.rs_signFunc) { + var data = this.rs_lines.join('\n'); + var self = this; + this.rs_signFunc(data, function (err, sig) { + if (err) { + cb(err); + return; + } + try { + assert.object(sig, 'signature'); + assert.string(sig.keyId, 'signature.keyId'); + assert.string(sig.algorithm, 'signature.algorithm'); + assert.string(sig.signature, 'signature.signature'); + alg = validateAlgorithm(sig.algorithm); - documentImpl.close(); - } + authz = sprintf(AUTHZ_FMT, + sig.keyId, + sig.algorithm, + self.rs_headers.join(' '), + sig.signature); + } catch (e) { + cb(e); + return; + } + cb(null, authz); + }); - get window() { - // It's important to grab the global proxy, instead of just the result of `createWindow(...)`, since otherwise - // things like `window.eval` don't exist. - return this[window]._globalProxy; + } else { + try { + var sigObj = this.rs_signer.sign(); + } catch (e) { + cb(e); + return; + } + alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm; + var signature = sigObj.toString(); + authz = sprintf(AUTHZ_FMT, + this.rs_keyId, + alg, + this.rs_headers.join(' '), + signature); + cb(null, authz); } +}; - get virtualConsole() { - return this[window]._virtualConsole; - } +///--- Exported API - get cookieJar() { - // TODO NEWAPI move _cookieJar to window probably - return idlUtils.implForWrapper(this[window]._document)._cookieJar; - } +module.exports = { + /** + * Identifies whether a given object is a request signer or not. + * + * @param {Object} object, the object to identify + * @returns {Boolean} + */ + isSigner: function (obj) { + if (typeof (obj) === 'object' && obj instanceof RequestSigner) + return (true); + return (false); + }, - serialize() { - return fragmentSerialization(idlUtils.implForWrapper(this[window]._document), { requireWellFormed: false }); - } + /** + * Creates a request signer, used to asynchronously build a signature + * for a request (does not have to be an http.ClientRequest). + * + * @param {Object} options, either: + * - {String} keyId + * - {String|Buffer} key + * - {String} algorithm (optional, required for HMAC) + * or: + * - {Func} sign (data, cb) + * @return {RequestSigner} + */ + createSigner: function createSigner(options) { + return (new RequestSigner(options)); + }, - nodeLocation(node) { - if (!idlUtils.implForWrapper(this[window]._document)._parseOptions.sourceCodeLocationInfo) { - throw new Error("Location information was not saved for this jsdom. Use includeNodeLocations during creation."); - } + /** + * Adds an 'Authorization' header to an http.ClientRequest object. + * + * Note that this API will add a Date header if it's not already set. Any + * other headers in the options.headers array MUST be present, or this + * will throw. + * + * You shouldn't need to check the return type; it's just there if you want + * to be pedantic. + * + * The optional flag indicates whether parsing should use strict enforcement + * of the version draft-cavage-http-signatures-04 of the spec or beyond. + * The default is to be loose and support + * older versions for compatibility. + * + * @param {Object} request an instance of http.ClientRequest. + * @param {Object} options signing parameters object: + * - {String} keyId required. + * - {String} key required (either a PEM or HMAC key). + * - {Array} headers optional; defaults to ['date']. + * - {String} algorithm optional (unless key is HMAC); + * default is the same as the sshpk default + * signing algorithm for the type of key given + * - {String} httpVersion optional; defaults to '1.1'. + * - {Boolean} strict optional; defaults to 'false'. + * @return {Boolean} true if Authorization (and optionally Date) were added. + * @throws {TypeError} on bad parameter types (input). + * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with + * the given key. + * @throws {sshpk.KeyParseError} if key was bad. + * @throws {MissingHeaderError} if a header to be signed was specified but + * was not present. + */ + signRequest: function signRequest(request, options) { + assert.object(request, 'request'); + assert.object(options, 'options'); + assert.optionalString(options.algorithm, 'options.algorithm'); + assert.string(options.keyId, 'options.keyId'); + assert.optionalArrayOfString(options.headers, 'options.headers'); + assert.optionalString(options.httpVersion, 'options.httpVersion'); - return idlUtils.implForWrapper(node).sourceCodeLocation; - } + if (!request.getHeader('Date')) + request.setHeader('Date', jsprim.rfc1123(new Date())); + if (!options.headers) + options.headers = ['date']; + if (!options.httpVersion) + options.httpVersion = '1.1'; - getInternalVMContext() { - if (!vm.isContext(this[window])) { - throw new TypeError("This jsdom was not configured to allow script running. " + - "Use the runScripts option during creation."); + var alg = []; + if (options.algorithm) { + options.algorithm = options.algorithm.toLowerCase(); + alg = validateAlgorithm(options.algorithm); } - return this[window]; - } - - reconfigure(settings) { - if ("windowTop" in settings) { - this[window]._top = settings.windowTop; - } + var i; + var stringToSign = ''; + for (i = 0; i < options.headers.length; i++) { + if (typeof (options.headers[i]) !== 'string') + throw new TypeError('options.headers must be an array of Strings'); - if ("url" in settings) { - const document = idlUtils.implForWrapper(this[window]._document); + var h = options.headers[i].toLowerCase(); - const url = whatwgURL.parseURL(settings.url); - if (url === null) { - throw new TypeError(`Could not parse "${settings.url}" as a URL`); + if (h === 'request-line') { + if (!options.strict) { + /** + * We allow headers from the older spec drafts if strict parsing isn't + * specified in options. + */ + stringToSign += + request.method + ' ' + request.path + ' HTTP/' + + options.httpVersion; + } else { + /* Strict parsing doesn't allow older draft headers. */ + throw (new StrictParsingError('request-line is not a valid header ' + + 'with strict parsing enabled.')); + } + } else if (h === '(request-target)') { + stringToSign += + '(request-target): ' + request.method.toLowerCase() + ' ' + + request.path; + } else { + var value = request.getHeader(h); + if (value === undefined || value === '') { + throw new MissingHeaderError(h + ' was not in the request'); + } + stringToSign += h + ': ' + value; } - document._URL = url; - document._origin = whatwgURL.serializeURLOrigin(document._URL); + if ((i + 1) < options.headers.length) + stringToSign += '\n'; } - } - static fragment(string = "") { - if (!sharedFragmentDocument) { - sharedFragmentDocument = (new JSDOM()).window.document; + /* This is just for unit tests. */ + if (request.hasOwnProperty('_stringToSign')) { + request._stringToSign = stringToSign; } - const template = sharedFragmentDocument.createElement("template"); - template.innerHTML = string; - return template.content; - } + var signature; + if (alg[0] === 'hmac') { + if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) + throw (new TypeError('options.key must be a string or Buffer')); - static fromURL(url, options = {}) { - return Promise.resolve().then(() => { - // Remove the hash while sending this through the research loader fetch(). - // It gets added back a few lines down when constructing the JSDOM object. - const parsedURL = new URL(url); - const originalHash = parsedURL.hash; - parsedURL.hash = ""; - url = parsedURL.href; + var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key); + hmac.update(stringToSign); + signature = hmac.digest('base64'); - options = normalizeFromURLOptions(options); + } else { + var key = options.key; + if (typeof (key) === 'string' || Buffer.isBuffer(key)) + key = sshpk.parsePrivateKey(options.key); - const resourceLoader = resourcesToResourceLoader(options.resources); - const resourceLoaderForInitialRequest = resourceLoader.constructor === NoOpResourceLoader ? - new ResourceLoader() : - resourceLoader; + assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), + 'options.key must be a sshpk.PrivateKey'); - const req = resourceLoaderForInitialRequest.fetch(url, { - accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", - cookieJar: options.cookieJar, - referrer: options.referrer - }); + if (!PK_ALGOS[key.type]) { + throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + + 'keys are not supported')); + } - return req.then(body => { - const res = req.response; + if (alg[0] !== undefined && key.type !== alg[0]) { + throw (new InvalidAlgorithmError('options.key must be a ' + + alg[0].toUpperCase() + ' key, was given a ' + + key.type.toUpperCase() + ' key instead')); + } - options = Object.assign(options, { - url: req.href + originalHash, - contentType: res.headers["content-type"], - referrer: req.getHeader("referer") - }); + var signer = key.createSign(alg[1]); + signer.update(stringToSign); + var sigObj = signer.sign(); + if (!HASH_ALGOS[sigObj.hashAlgorithm]) { + throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() + + ' is not a supported hash algorithm')); + } + options.algorithm = key.type + '-' + sigObj.hashAlgorithm; + signature = sigObj.toString(); + assert.notStrictEqual(signature, '', 'empty signature produced'); + } - return new JSDOM(body, options); - }); - }); - } + var authzHeaderName = options.authorizationHeaderName || 'Authorization'; - static async fromFile(filename, options = {}) { - options = normalizeFromFileOptions(filename, options); - const buffer = await fs.readFile(filename); + request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT, + options.keyId, + options.algorithm, + options.headers.join(' '), + signature)); - return new JSDOM(buffer, options); + return true; } -} -function normalizeFromURLOptions(options) { - // Checks on options that are invalid for `fromURL` - if (options.url !== undefined) { - throw new TypeError("Cannot supply a url option when using fromURL"); - } - if (options.contentType !== undefined) { - throw new TypeError("Cannot supply a contentType option when using fromURL"); - } +}; - // Normalization of options which must be done before the rest of the fromURL code can use them, because they are - // given to request() - const normalized = { ...options }; - if (options.referrer !== undefined) { - normalized.referrer = (new URL(options.referrer)).href; - } +/***/ }), - if (options.cookieJar === undefined) { - normalized.cookieJar = new CookieJar(); - } +/***/ 65689: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return normalized; +// Copyright 2012 Joyent, Inc. All rights reserved. - // All other options don't need to be processed yet, and can be taken care of in the normal course of things when - // `fromURL` calls `new JSDOM(html, options)`. -} +var assert = __nccwpck_require__(66631); +var sshpk = __nccwpck_require__(87022); +var util = __nccwpck_require__(73837); -function normalizeFromFileOptions(filename, options) { - const normalized = { ...options }; +var HASH_ALGOS = { + 'sha1': true, + 'sha256': true, + 'sha512': true +}; - if (normalized.contentType === undefined) { - const extname = path.extname(filename); - if (extname === ".xhtml" || extname === ".xht" || extname === ".xml") { - normalized.contentType = "application/xhtml+xml"; - } - } +var PK_ALGOS = { + 'rsa': true, + 'dsa': true, + 'ecdsa': true +}; - if (normalized.url === undefined) { - normalized.url = new URL("file:" + path.resolve(filename)); - } +function HttpSignatureError(message, caller) { + if (Error.captureStackTrace) + Error.captureStackTrace(this, caller || HttpSignatureError); - return normalized; + this.message = message; + this.name = caller.name; } +util.inherits(HttpSignatureError, Error); -function transformOptions(options, encoding, mimeType) { - const transformed = { - windowOptions: { - // Defaults - url: "about:blank", - referrer: "", - contentType: "text/html", - parsingMode: "html", - parseOptions: { - sourceCodeLocationInfo: false, - scriptingEnabled: false - }, - runScripts: undefined, - encoding, - pretendToBeVisual: false, - storageQuota: 5000000, - - // Defaults filled in later - resourceLoader: undefined, - virtualConsole: undefined, - cookieJar: undefined - }, +function InvalidAlgorithmError(message) { + HttpSignatureError.call(this, message, InvalidAlgorithmError); +} +util.inherits(InvalidAlgorithmError, HttpSignatureError); - // Defaults - beforeParse() { } - }; +function validateAlgorithm(algorithm) { + var alg = algorithm.toLowerCase().split('-'); - // options.contentType was parsed into mimeType by the caller. - if (!mimeType.isHTML() && !mimeType.isXML()) { - throw new RangeError(`The given content type of "${options.contentType}" was not a HTML or XML content type`); + if (alg.length !== 2) { + throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' + + 'valid algorithm')); } - transformed.windowOptions.contentType = mimeType.essence; - transformed.windowOptions.parsingMode = mimeType.isHTML() ? "html" : "xml"; - - if (options.url !== undefined) { - transformed.windowOptions.url = (new URL(options.url)).href; + if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) { + throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' + + 'are not supported')); } - if (options.referrer !== undefined) { - transformed.windowOptions.referrer = (new URL(options.referrer)).href; + if (!HASH_ALGOS[alg[1]]) { + throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' + + 'supported hash algorithm')); } - if (options.includeNodeLocations) { - if (transformed.windowOptions.parsingMode === "xml") { - throw new TypeError("Cannot set includeNodeLocations to true with an XML content type"); - } + return (alg); +} - transformed.windowOptions.parseOptions = { sourceCodeLocationInfo: true }; - } +///--- API - transformed.windowOptions.cookieJar = options.cookieJar === undefined ? - new CookieJar() : - options.cookieJar; +module.exports = { - transformed.windowOptions.virtualConsole = options.virtualConsole === undefined ? - (new VirtualConsole()).sendTo(console) : - options.virtualConsole; + HASH_ALGOS: HASH_ALGOS, + PK_ALGOS: PK_ALGOS, - if (!(transformed.windowOptions.virtualConsole instanceof VirtualConsole)) { - throw new TypeError("virtualConsole must be an instance of VirtualConsole"); - } + HttpSignatureError: HttpSignatureError, + InvalidAlgorithmError: InvalidAlgorithmError, - transformed.windowOptions.resourceLoader = resourcesToResourceLoader(options.resources); + validateAlgorithm: validateAlgorithm, - if (options.runScripts !== undefined) { - transformed.windowOptions.runScripts = String(options.runScripts); - if (transformed.windowOptions.runScripts === "dangerously") { - transformed.windowOptions.parseOptions.scriptingEnabled = true; - } else if (transformed.windowOptions.runScripts !== "outside-only") { - throw new RangeError(`runScripts must be undefined, "dangerously", or "outside-only"`); - } - } + /** + * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. + * + * The intent of this module is to interoperate with OpenSSL only, + * specifically the node crypto module's `verify` method. + * + * @param {String} key an OpenSSH public key. + * @return {String} PEM encoded form of the RSA public key. + * @throws {TypeError} on bad input. + * @throws {Error} on invalid ssh key formatted data. + */ + sshKeyToPEM: function sshKeyToPEM(key) { + assert.string(key, 'ssh_key'); - if (options.beforeParse !== undefined) { - transformed.beforeParse = options.beforeParse; - } + var k = sshpk.parseKey(key, 'ssh'); + return (k.toString('pem')); + }, - if (options.pretendToBeVisual !== undefined) { - transformed.windowOptions.pretendToBeVisual = Boolean(options.pretendToBeVisual); - } - if (options.storageQuota !== undefined) { - transformed.windowOptions.storageQuota = Number(options.storageQuota); - } + /** + * Generates an OpenSSH fingerprint from an ssh public key. + * + * @param {String} key an OpenSSH public key. + * @return {String} key fingerprint. + * @throws {TypeError} on bad input. + * @throws {Error} if what you passed doesn't look like an ssh public key. + */ + fingerprint: function fingerprint(key) { + assert.string(key, 'ssh_key'); - return transformed; -} + var k = sshpk.parseKey(key, 'ssh'); + return (k.fingerprint('md5').toString('hex')); + }, -function normalizeHTML(html, mimeType) { - let encoding = "UTF-8"; + /** + * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa) + * + * The reverse of the above function. + */ + pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) { + assert.equal('string', typeof (pem), 'typeof pem'); - if (ArrayBuffer.isView(html)) { - html = Buffer.from(html.buffer, html.byteOffset, html.byteLength); - } else if (html instanceof ArrayBuffer) { - html = Buffer.from(html); + var k = sshpk.parseKey(pem, 'pem'); + k.comment = comment; + return (k.toString('ssh')); } +}; - if (Buffer.isBuffer(html)) { - encoding = sniffHTMLEncoding(html, { - defaultEncoding: mimeType.isXML() ? "UTF-8" : "windows-1252", - transportLayerEncodingLabel: mimeType.parameters.get("charset") - }); - html = whatwgEncoding.decode(html, encoding); - } else { - html = String(html); - } - return { html, encoding }; -} +/***/ }), -function resourcesToResourceLoader(resources) { - switch (resources) { - case undefined: { - return new NoOpResourceLoader(); - } - case "usable": { - return new ResourceLoader(); - } - default: { - if (!(resources instanceof ResourceLoader)) { - throw new TypeError("resources must be an instance of ResourceLoader"); - } - return resources; - } - } -} +/***/ 51227: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -exports.JSDOM = JSDOM; +// Copyright 2015 Joyent, Inc. -exports.VirtualConsole = VirtualConsole; -exports.CookieJar = CookieJar; -exports.ResourceLoader = ResourceLoader; +var assert = __nccwpck_require__(66631); +var crypto = __nccwpck_require__(6113); +var sshpk = __nccwpck_require__(87022); +var utils = __nccwpck_require__(65689); -exports.toughCookie = toughCookie; +var HASH_ALGOS = utils.HASH_ALGOS; +var PK_ALGOS = utils.PK_ALGOS; +var InvalidAlgorithmError = utils.InvalidAlgorithmError; +var HttpSignatureError = utils.HttpSignatureError; +var validateAlgorithm = utils.validateAlgorithm; +///--- Exported API -/***/ }), +module.exports = { + /** + * Verify RSA/DSA signature against public key. You are expected to pass in + * an object that was returned from `parse()`. + * + * @param {Object} parsedSignature the object you got from `parse`. + * @param {String} pubkey RSA/DSA private key PEM. + * @return {Boolean} true if valid, false otherwise. + * @throws {TypeError} if you pass in bad arguments. + * @throws {InvalidAlgorithmError} + */ + verifySignature: function verifySignature(parsedSignature, pubkey) { + assert.object(parsedSignature, 'parsedSignature'); + if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey)) + pubkey = sshpk.parseKey(pubkey); + assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key'); -/***/ 55802: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var alg = validateAlgorithm(parsedSignature.algorithm); + if (alg[0] === 'hmac' || alg[0] !== pubkey.type) + return (false); -"use strict"; + var v = pubkey.createVerify(alg[1]); + v.update(parsedSignature.signingString); + return (v.verify(parsedSignature.params.signature, 'base64')); + }, -const vm = __nccwpck_require__(92184); -const webIDLConversions = __nccwpck_require__(54886); -const { CSSStyleDeclaration } = __nccwpck_require__(15674); -const { Performance: RawPerformance } = __nccwpck_require__(38481); -const notImplemented = __nccwpck_require__(42751); -const { installInterfaces } = __nccwpck_require__(71643); -const { define, mixin } = __nccwpck_require__(11463); -const Element = __nccwpck_require__(4444); -const EventTarget = __nccwpck_require__(71038); -const EventHandlerNonNull = __nccwpck_require__(23129); -const OnBeforeUnloadEventHandlerNonNull = __nccwpck_require__(64546); -const OnErrorEventHandlerNonNull = __nccwpck_require__(87517); -const PageTransitionEvent = __nccwpck_require__(32941); -const namedPropertiesWindow = __nccwpck_require__(15200); -const postMessage = __nccwpck_require__(47054); -const DOMException = __nccwpck_require__(57617); -const { btoa, atob } = __nccwpck_require__(75696); -const idlUtils = __nccwpck_require__(34908); -const WebSocketImpl = __nccwpck_require__(13846).implementation; -const BarProp = __nccwpck_require__(35849); -const documents = __nccwpck_require__(19951); -const External = __nccwpck_require__(19995); -const Navigator = __nccwpck_require__(96340); -const Performance = __nccwpck_require__(19264); -const Screen = __nccwpck_require__(46164); -const Storage = __nccwpck_require__(76969); -const Selection = __nccwpck_require__(69144); -const reportException = __nccwpck_require__(15612); -const { getCurrentEventHandlerValue } = __nccwpck_require__(50238); -const { fireAnEvent } = __nccwpck_require__(45673); -const SessionHistory = __nccwpck_require__(14825); -const { forEachMatchingSheetRuleOfElement, getResolvedValue, propertiesWithResolvedValueImplemented, - SHADOW_DOM_PSEUDO_REGEXP } = __nccwpck_require__(11627); -const CustomElementRegistry = __nccwpck_require__(17609); -const jsGlobals = __nccwpck_require__(70629); + /** + * Verify HMAC against shared secret. You are expected to pass in an object + * that was returned from `parse()`. + * + * @param {Object} parsedSignature the object you got from `parse`. + * @param {String} secret HMAC shared secret. + * @return {Boolean} true if valid, false otherwise. + * @throws {TypeError} if you pass in bad arguments. + * @throws {InvalidAlgorithmError} + */ + verifyHMAC: function verifyHMAC(parsedSignature, secret) { + assert.object(parsedSignature, 'parsedHMAC'); + assert.string(secret, 'secret'); -const GlobalEventHandlersImpl = __nccwpck_require__(4084).implementation; -const WindowEventHandlersImpl = __nccwpck_require__(55974).implementation; + var alg = validateAlgorithm(parsedSignature.algorithm); + if (alg[0] !== 'hmac') + return (false); -const events = new Set([ - // GlobalEventHandlers - "abort", "autocomplete", - "autocompleteerror", "blur", - "cancel", "canplay", "canplaythrough", - "change", "click", - "close", "contextmenu", - "cuechange", "dblclick", - "drag", "dragend", - "dragenter", - "dragleave", "dragover", - "dragstart", "drop", - "durationchange", "emptied", - "ended", "focus", - "input", "invalid", - "keydown", "keypress", - "keyup", "load", "loadeddata", - "loadedmetadata", "loadstart", - "mousedown", "mouseenter", - "mouseleave", "mousemove", - "mouseout", "mouseover", - "mouseup", "wheel", - "pause", "play", - "playing", "progress", - "ratechange", "reset", - "resize", "scroll", - "securitypolicyviolation", - "seeked", "seeking", - "select", "sort", "stalled", - "submit", "suspend", - "timeupdate", "toggle", - "volumechange", "waiting", + var hashAlg = alg[1].toUpperCase(); - // WindowEventHandlers - "afterprint", - "beforeprint", - "hashchange", - "languagechange", - "message", - "messageerror", - "offline", - "online", - "pagehide", - "pageshow", - "popstate", - "rejectionhandled", - "storage", - "unhandledrejection", - "unload" + var hmac = crypto.createHmac(hashAlg, secret); + hmac.update(parsedSignature.signingString); - // "error" and "beforeunload" are added separately -]); + /* + * Now double-hash to avoid leaking timing information - there's + * no easy constant-time compare in JS, so we use this approach + * instead. See for more info: + * https://www.isecpartners.com/blog/2011/february/double-hmac- + * verification.aspx + */ + var h1 = crypto.createHmac(hashAlg, secret); + h1.update(hmac.digest()); + h1 = h1.digest(); + var h2 = crypto.createHmac(hashAlg, secret); + h2.update(new Buffer(parsedSignature.params.signature, 'base64')); + h2 = h2.digest(); -exports.createWindow = function (options) { - return new Window(options); -}; + /* Node 0.8 returns strings from .digest(). */ + if (typeof (h1) === 'string') + return (h1 === h2); + /* And node 0.10 lacks the .equals() method on Buffers. */ + if (Buffer.isBuffer(h1) && !h1.equals) + return (h1.toString('binary') === h2.toString('binary')); -const jsGlobalEntriesToInstall = Object.entries(jsGlobals).filter(([name]) => name in global); + return (h1.equals(h2)); + } +}; -// TODO remove when we drop Node v10 support. -const anyNodeVersionQueueMicrotask = typeof queueMicrotask === "function" ? queueMicrotask : process.nextTick; -// https://html.spec.whatwg.org/#the-window-object -function setupWindow(windowInstance, { runScripts }) { - if (runScripts === "outside-only" || runScripts === "dangerously") { - contextifyWindow(windowInstance); +/***/ }), - // Without this, these globals will only appear to scripts running inside the context using vm.runScript; they will - // not appear to scripts running from the outside, including to JSDOM implementation code. - for (const [globalName, globalPropDesc] of jsGlobalEntriesToInstall) { - const propDesc = { ...globalPropDesc, value: vm.runInContext(globalName, windowInstance) }; - Object.defineProperty(windowInstance, globalName, propDesc); - } - } else { - // Without contextifying the window, none of the globals will exist. So, let's at least alias them from the Node.js - // context. See https://github.com/jsdom/jsdom/issues/2727 for more background and discussion. - for (const [globalName, globalPropDesc] of jsGlobalEntriesToInstall) { - const propDesc = { ...globalPropDesc, value: global[globalName] }; - Object.defineProperty(windowInstance, globalName, propDesc); - } - } +/***/ 39695: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - installInterfaces(windowInstance, ["Window"]); +"use strict"; - const EventTargetConstructor = windowInstance.EventTarget; +var Buffer = (__nccwpck_require__(15118).Buffer); - // eslint-disable-next-line func-name-matching, func-style, no-shadow - const windowConstructor = function Window() { - throw new TypeError("Illegal constructor"); - }; - Object.setPrototypeOf(windowConstructor, EventTargetConstructor); +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. - Object.defineProperty(windowInstance, "Window", { - configurable: true, - writable: true, - value: windowConstructor - }); +exports._dbcs = DBCSCodec; - const windowPrototype = Object.create(EventTargetConstructor.prototype); - Object.defineProperties(windowPrototype, { - constructor: { - value: windowConstructor, - writable: true, - configurable: true - }, - [Symbol.toStringTag]: { - value: "Window", - configurable: true - } - }); +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; - windowConstructor.prototype = windowPrototype; - Object.setPrototypeOf(windowInstance, windowPrototype); +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; - EventTarget.setup(windowInstance, windowInstance); - mixin(windowInstance, WindowEventHandlersImpl.prototype); - mixin(windowInstance, GlobalEventHandlersImpl.prototype); - windowInstance._initGlobalEvents(); - Object.defineProperty(windowInstance, "onbeforeunload", { - configurable: true, - enumerable: true, - get() { - return idlUtils.tryWrapperForImpl(getCurrentEventHandlerValue(this, "beforeunload")); - }, - set(V) { - if (!idlUtils.isObject(V)) { - V = null; - } else { - V = OnBeforeUnloadEventHandlerNonNull.convert(V, { - context: "Failed to set the 'onbeforeunload' property on 'Window': The provided value" - }); - } - this._setEventHandlerFor("beforeunload", V); - } - }); +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); - Object.defineProperty(windowInstance, "onerror", { - configurable: true, - enumerable: true, - get() { - return idlUtils.tryWrapperForImpl(getCurrentEventHandlerValue(this, "error")); - }, - set(V) { - if (!idlUtils.isObject(V)) { - V = null; - } else { - V = OnErrorEventHandlerNonNull.convert(V, { - context: "Failed to set the 'onerror' property on 'Window': The provided value" - }); - } - this._setEventHandlerFor("error", V); - } - }); + // Load tables. + var mappingTable = codecOptions.table(); - for (const event of events) { - Object.defineProperty(windowInstance, `on${event}`, { - configurable: true, - enumerable: true, - get() { - return idlUtils.tryWrapperForImpl(getCurrentEventHandlerValue(this, event)); - }, - set(V) { - if (!idlUtils.isObject(V)) { - V = null; - } else { - V = EventHandlerNonNull.convert(V, { - context: `Failed to set the 'on${event}' property on 'Window': The provided value` - }); - } - this._setEventHandlerFor(event, V); - } - }); - } - windowInstance._globalObject = windowInstance; -} + // Decode tables: MBCS -> Unicode. -// NOTE: per https://heycam.github.io/webidl/#Global, all properties on the Window object must be own-properties. -// That is why we assign everything inside of the constructor, instead of using a shared prototype. -// You can verify this in e.g. Firefox or Internet Explorer, which do a good job with Web IDL compliance. -function Window(options) { - setupWindow(this, { runScripts: options.runScripts }); + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. - const rawPerformance = new RawPerformance(); - const windowInitialized = rawPerformance.now(); + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; - const window = this; + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); - // ### PRIVATE DATA PROPERTIES + this.defaultCharUnicode = iconv.defaultCharUnicode; - this._resourceLoader = options.resourceLoader; + + // Encode tables: Unicode -> DBCS. - // vm initialization is deferred until script processing is activated - this._globalProxy = this; - Object.defineProperty(idlUtils.implForWrapper(this), idlUtils.wrapperSymbol, { get: () => this._globalProxy }); + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; - // List options explicitly to be clear which are passed through - this._document = documents.createWrapper(window, { - parsingMode: options.parsingMode, - contentType: options.contentType, - encoding: options.encoding, - cookieJar: options.cookieJar, - url: options.url, - lastModified: options.lastModified, - referrer: options.referrer, - parseOptions: options.parseOptions, - defaultView: this._globalProxy, - global: this, - parentOrigin: options.parentOrigin - }, { alwaysUseDocumentClass: true }); + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); - if (vm.isContext(window)) { - const documentImpl = idlUtils.implForWrapper(window._document); - documentImpl._defaultView = window._globalProxy = vm.runInContext("this", window); - } + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + } - const documentOrigin = idlUtils.implForWrapper(this._document)._origin; - this._origin = documentOrigin; + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); - // https://html.spec.whatwg.org/#session-history - this._sessionHistory = new SessionHistory({ - document: idlUtils.implForWrapper(this._document), - url: idlUtils.implForWrapper(this._document)._URL, - stateObject: null - }, this); - this._virtualConsole = options.virtualConsole; + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. - this._runScripts = options.runScripts; + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); - // Set up the window as if it's a top level window. - // If it's not, then references will be corrected by frame/iframe code. - this._parent = this._top = this._globalProxy; - this._frameElement = null; + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); - // This implements window.frames.length, since window.frames returns a - // self reference to the window object. This value is incremented in the - // HTMLFrameElement implementation. - this._length = 0; + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } +} - // https://dom.spec.whatwg.org/#window-current-event - this._currentEvent = undefined; +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; - this._pretendToBeVisual = options.pretendToBeVisual; - this._storageQuota = options.storageQuota; +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); - // Some properties (such as localStorage and sessionStorage) share data - // between windows in the same origin. This object is intended - // to contain such data. - if (options.commonForOrigin && options.commonForOrigin[documentOrigin]) { - this._commonForOrigin = options.commonForOrigin; - } else { - this._commonForOrigin = { - [documentOrigin]: { - localStorageArea: new Map(), - sessionStorageArea: new Map(), - windowsInSameOrigin: [this] - } - }; - } + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; - this._currentOriginData = this._commonForOrigin[documentOrigin]; + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} - // ### WEB STORAGE - this._localStorage = Storage.create(window, [], { - associatedWindow: this, - storageArea: this._currentOriginData.localStorageArea, - type: "localStorage", - url: this._document.documentURI, - storageQuota: this._storageQuota - }); - this._sessionStorage = Storage.create(window, [], { - associatedWindow: this, - storageArea: this._currentOriginData.sessionStorageArea, - type: "sessionStorage", - url: this._document.documentURI, - storageQuota: this._storageQuota - }); +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); - // ### SELECTION + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; - // https://w3c.github.io/selection-api/#dfn-selection - this._selection = Selection.createImpl(window); + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. - // https://w3c.github.io/selection-api/#dom-window - this.getSelection = function () { - return window._selection; - }; + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} - // ### GETTERS +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} - const locationbar = BarProp.create(window); - const menubar = BarProp.create(window); - const personalbar = BarProp.create(window); - const scrollbars = BarProp.create(window); - const statusbar = BarProp.create(window); - const toolbar = BarProp.create(window); - const external = External.create(window); - const navigator = Navigator.create(window, [], { userAgent: this._resourceLoader._userAgent }); - const performance = Performance.create(window, [], { rawPerformance }); - const screen = Screen.create(window); - const customElementRegistry = CustomElementRegistry.create(window); +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} - define(this, { - get length() { - return window._length; - }, - get window() { - return window._globalProxy; - }, - get frameElement() { - return idlUtils.wrapperForImpl(window._frameElement); - }, - get frames() { - return window._globalProxy; - }, - get self() { - return window._globalProxy; - }, - get parent() { - return window._parent; - }, - get top() { - return window._top; - }, - get document() { - return window._document; - }, - get external() { - return external; - }, - get location() { - return idlUtils.wrapperForImpl(idlUtils.implForWrapper(window._document)._location); - }, - get history() { - return idlUtils.wrapperForImpl(idlUtils.implForWrapper(window._document)._history); - }, - get navigator() { - return navigator; - }, - get locationbar() { - return locationbar; - }, - get menubar() { - return menubar; - }, - get personalbar() { - return personalbar; - }, - get scrollbars() { - return scrollbars; - }, - get statusbar() { - return statusbar; - }, - get toolbar() { - return toolbar; - }, - get performance() { - return performance; - }, - get screen() { - return screen; - }, - get origin() { - return window._origin; - }, - // The origin IDL attribute is defined with [Replaceable]. - set origin(value) { - Object.defineProperty(this, "origin", { - value, - writable: true, - enumerable: true, - configurable: true - }); - }, - get localStorage() { - if (idlUtils.implForWrapper(this._document)._origin === "null") { - throw DOMException.create(window, [ - "localStorage is not available for opaque origins", - "SecurityError" - ]); - } +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; - return this._localStorage; - }, - get sessionStorage() { - if (idlUtils.implForWrapper(this._document)._origin === "null") { - throw DOMException.create(window, [ - "sessionStorage is not available for opaque origins", - "SecurityError" - ]); - } + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } - return this._sessionStorage; - }, - get customElements() { - return customElementRegistry; - }, - get event() { - return window._currentEvent ? idlUtils.wrapperForImpl(window._currentEvent) : undefined; - }, - set event(value) { - Object.defineProperty(window, "event", { configurable: true, enumerable: true, writable: true, value }); + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } } - }); - namedPropertiesWindow.initializeWindow(this, this._globalProxy); + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} - // ### METHODS +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; - // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +} - // In the spec the list of active timers is a set of IDs. We make it a map of IDs to Node.js timer objects, so that - // we can call Node.js-side clearTimeout() when clearing, and thus allow process shutdown faster. - const listOfActiveTimers = new Map(); - let latestTimerId = 0; - this.setTimeout = function (handler, timeout = 0, ...args) { - if (typeof handler !== "function") { - handler = webIDLConversions.DOMString(handler); - } - timeout = webIDLConversions.long(timeout); - return timerInitializationSteps(handler, timeout, args, { methodContext: window, repeat: false }); - }; - this.setInterval = function (handler, timeout = 0, ...args) { - if (typeof handler !== "function") { - handler = webIDLConversions.DOMString(handler); - } - timeout = webIDLConversions.long(timeout); +// == Encoder ================================================================== - return timerInitializationSteps(handler, timeout, args, { methodContext: window, repeat: true }); - }; +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; +} - this.clearTimeout = function (handle = 0) { - handle = webIDLConversions.long(handle); +DBCSEncoder.prototype.write = function(str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; - const nodejsTimer = listOfActiveTimers.get(handle); - if (nodejsTimer) { - clearTimeout(nodejsTimer); - listOfActiveTimers.delete(handle); - } - }; - this.clearInterval = function (handle = 0) { - handle = webIDLConversions.long(handle); + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } - const nodejsTimer = listOfActiveTimers.get(handle); - if (nodejsTimer) { - // We use setTimeout() in timerInitializationSteps even for this.setInterval(). - clearTimeout(nodejsTimer); - listOfActiveTimers.delete(handle); - } - }; + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } - function timerInitializationSteps(handler, timeout, args, { methodContext, repeat, previousHandle }) { - // This appears to be unspecced, but matches browser behavior for close()ed windows. - if (!methodContext._document) { - return 0; - } + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; - // TODO: implement timer nesting level behavior. + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; - const methodContextProxy = methodContext._globalProxy; - const handle = previousHandle !== undefined ? previousHandle : ++latestTimerId; + } else if (resCode == undefined) { // Current character is not part of the sequence. - function task() { - if (!listOfActiveTimers.has(handle)) { - return; - } + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. - try { - if (typeof handler === "function") { - handler.apply(methodContextProxy, args); - } else if (window._runScripts === "dangerously") { - vm.runInContext(handler, window, { filename: window.location.href, displayErrors: false }); + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; } - } catch (e) { - reportException(window, e, window.location.href); - } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } - if (listOfActiveTimers.has(handle)) { - if (repeat) { - timerInitializationSteps(handler, timeout, args, { methodContext, repeat: true, previousHandle: handle }); - } else { - listOfActiveTimers.delete(handle); + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } } - } - } - if (timeout < 0) { - timeout = 0; + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } } - const nodejsTimer = setTimeout(task, timeout); - listOfActiveTimers.set(handle, nodejsTimer); - - return handle; - } + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} - // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#microtask-queuing +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. - this.queueMicrotask = function (callback) { - callback = webIDLConversions.Function(callback); + var newBuf = Buffer.alloc(10), j = 0; - anyNodeVersionQueueMicrotask(() => { - try { - callback(); - } catch (e) { - reportException(window, e, window.location.href); - } - }); - }; + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined; + } - // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#animation-frames + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); +} - let animationFrameCallbackId = 0; - const mapOfAnimationFrameCallbacks = new Map(); - let animationFrameNodejsInterval = null; +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; - // Unlike the spec, where an animation frame happens every 60 Hz regardless, we optimize so that if there are no - // requestAnimationFrame() calls outstanding, we don't fire the timer. This helps us track that. - let numberOfOngoingAnimationFrameCallbacks = 0; - if (this._pretendToBeVisual) { - this.requestAnimationFrame = function (callback) { - callback = webIDLConversions.Function(callback); +// == Decoder ================================================================== - const handle = ++animationFrameCallbackId; - mapOfAnimationFrameCallbacks.set(handle, callback); +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = Buffer.alloc(0); - ++numberOfOngoingAnimationFrameCallbacks; - if (numberOfOngoingAnimationFrameCallbacks === 1) { - animationFrameNodejsInterval = setInterval(() => { - runAnimationFrameCallbacks(rawPerformance.now() - windowInitialized); - }, 1000 / 60); - } + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} - return handle; - }; +DBCSDecoder.prototype.write = function(buf) { + var newBuf = Buffer.alloc(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; - this.cancelAnimationFrame = function (handle) { - handle = webIDLConversions["unsigned long"](handle); + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; - removeAnimationFrameCallback(handle); - }; + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; - function runAnimationFrameCallbacks(now) { - // Converting to an array is important to get a sync snapshot and thus match spec semantics. - const callbackHandles = [...mapOfAnimationFrameCallbacks.keys()]; - for (const handle of callbackHandles) { - // This has() can be false if a callback calls cancelAnimationFrame(). - if (mapOfAnimationFrameCallbacks.has(handle)) { - const callback = mapOfAnimationFrameCallbacks.get(handle); - removeAnimationFrameCallback(handle); - try { - callback(now); - } catch (e) { - reportException(window, e, window.location.href); - } + if (uCode >= 0) { + // Normal character, just use it. } - } - } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); + } + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); - function removeAnimationFrameCallback(handle) { - if (mapOfAnimationFrameCallbacks.has(handle)) { - --numberOfOngoingAnimationFrameCallbacks; - if (numberOfOngoingAnimationFrameCallbacks === 0) { - clearInterval(animationFrameNodejsInterval); + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 + uCode % 0x400; } - } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; - mapOfAnimationFrameCallbacks.delete(handle); + // Reset trie node. + nodeIdx = 0; seqStart = i+1; } - } - function stopAllTimers() { - for (const nodejsTimer of listOfActiveTimers.values()) { - clearTimeout(nodejsTimer); - } - listOfActiveTimers.clear(); + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} - clearInterval(animationFrameNodejsInterval); - } +DBCSDecoder.prototype.end = function() { + var ret = ''; - function Option(text, value, defaultSelected, selected) { - if (text === undefined) { - text = ""; - } - text = webIDLConversions.DOMString(text); + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); - if (value !== undefined) { - value = webIDLConversions.DOMString(value); + // Parse remaining as usual. + this.prevBuf = Buffer.alloc(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); } - defaultSelected = webIDLConversions.boolean(defaultSelected); - selected = webIDLConversions.boolean(selected); + this.nodeIdx = 0; + return ret; +} - const option = window._document.createElement("option"); - const impl = idlUtils.implForWrapper(option); - - if (text !== "") { - impl.text = text; - } - if (value !== undefined) { - impl.setAttributeNS(null, "value", value); - } - if (defaultSelected) { - impl.setAttributeNS(null, "selected", ""); - } - impl._selectedness = selected; - - return option; - } - Object.defineProperty(Option, "prototype", { - value: this.HTMLOptionElement.prototype, - configurable: false, - enumerable: false, - writable: false - }); - Object.defineProperty(window, "Option", { - value: Option, - configurable: true, - enumerable: false, - writable: true - }); - - function Image(...args) { - const img = window._document.createElement("img"); - const impl = idlUtils.implForWrapper(img); - - if (args.length > 0) { - impl.setAttributeNS(null, "width", String(args[0])); - } - if (args.length > 1) { - impl.setAttributeNS(null, "height", String(args[1])); - } - - return img; - } - Object.defineProperty(Image, "prototype", { - value: this.HTMLImageElement.prototype, - configurable: false, - enumerable: false, - writable: false - }); - Object.defineProperty(window, "Image", { - value: Image, - configurable: true, - enumerable: false, - writable: true - }); - - function Audio(src) { - const audio = window._document.createElement("audio"); - const impl = idlUtils.implForWrapper(audio); - impl.setAttributeNS(null, "preload", "auto"); - - if (src !== undefined) { - impl.setAttributeNS(null, "src", String(src)); - } - - return audio; - } - Object.defineProperty(Audio, "prototype", { - value: this.HTMLAudioElement.prototype, - configurable: false, - enumerable: false, - writable: false - }); - Object.defineProperty(window, "Audio", { - value: Audio, - configurable: true, - enumerable: false, - writable: true - }); - - this.postMessage = postMessage(window); - - this.atob = function (str) { - const result = atob(str); - if (result === null) { - throw DOMException.create(window, [ - "The string to be decoded contains invalid characters.", - "InvalidCharacterError" - ]); - } - return result; - }; - - this.btoa = function (str) { - const result = btoa(str); - if (result === null) { - throw DOMException.create(window, [ - "The string to be encoded contains invalid characters.", - "InvalidCharacterError" - ]); - } - return result; - }; - - this.stop = function () { - const manager = idlUtils.implForWrapper(this._document)._requestManager; - if (manager) { - manager.close(); - } - }; +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; - this.close = function () { - // Recursively close child frame windows, then ourselves (depth-first). - for (let i = 0; i < this.length; ++i) { - this[i].close(); + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; } + return l; +} - // Clear out all listeners. Any in-flight or upcoming events should not get delivered. - idlUtils.implForWrapper(this)._eventListeners = Object.create(null); - - if (this._document) { - if (this._document.body) { - this._document.body.innerHTML = ""; - } - - if (this._document.close) { - // It's especially important to clear out the listeners here because document.close() causes a "load" event to - // fire. - idlUtils.implForWrapper(this._document)._eventListeners = Object.create(null); - this._document.close(); - } - const doc = idlUtils.implForWrapper(this._document); - if (doc._requestManager) { - doc._requestManager.close(); - } - delete this._document; - } - stopAllTimers(); - WebSocketImpl.cleanUpWindow(this); - }; - this.getComputedStyle = function (elt, pseudoElt = undefined) { - elt = Element.convert(elt); - if (pseudoElt !== undefined && pseudoElt !== null) { - pseudoElt = webIDLConversions.DOMString(pseudoElt); - } +/***/ }), - if (pseudoElt !== undefined && pseudoElt !== null && pseudoElt !== "") { - // TODO: Parse pseudoElt +/***/ 91386: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (SHADOW_DOM_PSEUDO_REGEXP.test(pseudoElt)) { - throw new TypeError("Tried to get the computed style of a Shadow DOM pseudo-element."); - } +"use strict"; - notImplemented("window.computedStyle(elt, pseudoElt)", this); - } - const declaration = new CSSStyleDeclaration(); - const { forEach } = Array.prototype; - const { style } = elt; +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. - forEachMatchingSheetRuleOfElement(elt, rule => { - forEach.call(rule.style, property => { - declaration.setProperty( - property, - rule.style.getPropertyValue(property), - rule.style.getPropertyPriority(property) - ); - }); - }); +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) - // https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle - const declarations = Object.keys(propertiesWithResolvedValueImplemented); - forEach.call(declarations, property => { - declaration.setProperty(property, getResolvedValue(elt, property)); - }); + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html - forEach.call(style, property => { - declaration.setProperty(property, style.getPropertyValue(property), style.getPropertyPriority(property)); - }); + 'shiftjis': { + type: '_dbcs', + table: function() { return __nccwpck_require__(27014) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'ms31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + 'ms932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', - return declaration; - }; + 'eucjp': { + type: '_dbcs', + table: function() { return __nccwpck_require__(31532) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, - this.getSelection = function () { - return window._document.getSelection(); - }; + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. - // The captureEvents() and releaseEvents() methods must do nothing - this.captureEvents = function () {}; - this.releaseEvents = function () {}; + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder - // ### PUBLIC DATA PROPERTIES (TODO: should be getters) + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', - function wrapConsoleMethod(method) { - return (...args) => { - window._virtualConsole.emit(method, ...args); - }; - } + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return __nccwpck_require__(13336) }, + }, - this.console = { - assert: wrapConsoleMethod("assert"), - clear: wrapConsoleMethod("clear"), - count: wrapConsoleMethod("count"), - countReset: wrapConsoleMethod("countReset"), - debug: wrapConsoleMethod("debug"), - dir: wrapConsoleMethod("dir"), - dirxml: wrapConsoleMethod("dirxml"), - error: wrapConsoleMethod("error"), - group: wrapConsoleMethod("group"), - groupCollapsed: wrapConsoleMethod("groupCollapsed"), - groupEnd: wrapConsoleMethod("groupEnd"), - info: wrapConsoleMethod("info"), - log: wrapConsoleMethod("log"), - table: wrapConsoleMethod("table"), - time: wrapConsoleMethod("time"), - timeLog: wrapConsoleMethod("timeLog"), - timeEnd: wrapConsoleMethod("timeEnd"), - trace: wrapConsoleMethod("trace"), - warn: wrapConsoleMethod("warn") - }; + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return (__nccwpck_require__(13336).concat)(__nccwpck_require__(44346)) }, + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', - function notImplementedMethod(name) { - return function () { - notImplemented(name, window); - }; - } + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + 'gb18030': { + type: '_dbcs', + table: function() { return (__nccwpck_require__(13336).concat)(__nccwpck_require__(44346)) }, + gb18030: function() { return __nccwpck_require__(36258) }, + encodeSkipVals: [0x80], + encodeAdd: {'€': 0xA2E3}, + }, - define(this, { - name: "", - status: "", - devicePixelRatio: 1, - innerWidth: 1024, - innerHeight: 768, - outerWidth: 1024, - outerHeight: 768, - pageXOffset: 0, - pageYOffset: 0, - screenX: 0, - screenLeft: 0, - screenY: 0, - screenTop: 0, - scrollX: 0, - scrollY: 0, + 'chinese': 'gb18030', - alert: notImplementedMethod("window.alert"), - blur: notImplementedMethod("window.blur"), - confirm: notImplementedMethod("window.confirm"), - focus: notImplementedMethod("window.focus"), - moveBy: notImplementedMethod("window.moveBy"), - moveTo: notImplementedMethod("window.moveTo"), - open: notImplementedMethod("window.open"), - print: notImplementedMethod("window.print"), - prompt: notImplementedMethod("window.prompt"), - resizeBy: notImplementedMethod("window.resizeBy"), - resizeTo: notImplementedMethod("window.resizeTo"), - scroll: notImplementedMethod("window.scroll"), - scrollBy: notImplementedMethod("window.scrollBy"), - scrollTo: notImplementedMethod("window.scrollTo") - }); - // ### INITIALIZATION + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + 'ms949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return __nccwpck_require__(77348) }, + }, - process.nextTick(() => { - if (!window.document) { - return; // window might've been closed already - } + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', - const documentImpl = idlUtils.implForWrapper(window._document); - if (window.document.readyState === "complete") { - fireAnEvent("load", window, undefined, {}, documentImpl); - } else { - window.document.addEventListener("load", () => { - fireAnEvent("load", window, undefined, {}, documentImpl); + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. - if (!documentImpl._pageShowingFlag) { - documentImpl._pageShowingFlag = true; - fireAnEvent("pageshow", window, PageTransitionEvent, { persisted: false }, documentImpl); - } - }); - } - }); -} + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return __nccwpck_require__(74284) }, + }, -function contextifyWindow(window) { - if (vm.isContext(window)) { - return; - } + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return (__nccwpck_require__(74284).concat)(__nccwpck_require__(63480)) }, + encodeSkipVals: [0xa2cc], + }, - vm.createContext(window); -} + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', +}; /***/ }), -/***/ 89489: -/***/ ((module) => { - -// Ideally, we would use -// https://html.spec.whatwg.org/multipage/rendering.html#the-css-user-agent-style-sheet-and-presentational-hints -// but for now, just use the version from blink. This file is copied from -// https://chromium.googlesource.com/chromium/blink/+/96aa3a280ab7d67178c8f122a04949ce5f8579e0/Source/core/css/html.css -// (removed a line which had octal literals inside since octal literals are not allowed in template strings) - -// We use a .js file because otherwise we can't browserify this. (brfs is unusable due to lack of ES2015 support) - -module.exports = ` -/* - * The default style sheet used to render HTML. - * - * Copyright (C) 2000 Lars Knoll (knoll@kde.org) - * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ +/***/ 82733: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -@namespace "http://www.w3.org/1999/xhtml"; +"use strict"; -html { - display: block -} -:root { - scroll-blocks-on: start-touch wheel-event -} +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + __nccwpck_require__(12376), + __nccwpck_require__(11155), + __nccwpck_require__(51644), + __nccwpck_require__(26657), + __nccwpck_require__(41080), + __nccwpck_require__(21012), + __nccwpck_require__(39695), + __nccwpck_require__(91386), +]; -/* children of the element all have display:none */ -head { - display: none +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; } -meta { - display: none -} -title { - display: none -} +/***/ }), -link { - display: none -} +/***/ 12376: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -style { - display: none -} +"use strict"; -script { - display: none -} +var Buffer = (__nccwpck_require__(15118).Buffer); -/* generic block-level elements */ +// Export Node.js internal encodings. -body { - display: block; - margin: 8px -} +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", -p { - display: block; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1__qem; - -webkit-margin-start: 0; - -webkit-margin-end: 0; -} + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", -div { - display: block -} + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, -layer { - display: block -} + // Codec. + _internal: InternalCodec, +}; -article, aside, footer, header, hgroup, main, nav, section { - display: block -} +//------------------------------------------------------------------------------ -marquee { - display: inline-block; -} +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; -address { - display: block -} + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; -blockquote { - display: block; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; - -webkit-margin-start: 40px; - -webkit-margin-end: 40px; + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } + } } -figcaption { - display: block -} +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; -figure { - display: block; - -webkit-margin-before: 1em; - -webkit-margin-after: 1em; - -webkit-margin-start: 40px; - -webkit-margin-end: 40px; -} +//------------------------------------------------------------------------------ -q { - display: inline -} +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = (__nccwpck_require__(71576).StringDecoder); -/* nwmatcher does not support ::before and ::after, so we can't render q -correctly: https://html.spec.whatwg.org/multipage/rendering.html#phrasing-content-3 -TODO: add q::before and q::after selectors -*/ +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; -center { - display: block; - /* special centering to be able to emulate the html4/netscape behaviour */ - text-align: -webkit-center -} -hr { - display: block; - -webkit-margin-before: 0.5em; - -webkit-margin-after: 0.5em; - -webkit-margin-start: auto; - -webkit-margin-end: auto; - border-style: inset; - border-width: 1px; - box-sizing: border-box +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); } -map { - display: inline -} +InternalDecoder.prototype = StringDecoder.prototype; -video { - object-fit: contain; -} -/* heading elements */ +//------------------------------------------------------------------------------ +// Encoder is mostly trivial -h1 { - display: block; - font-size: 2em; - -webkit-margin-before: 0.67__qem; - -webkit-margin-after: 0.67em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold +function InternalEncoder(options, codec) { + this.enc = codec.enc; } -article h1, -aside h1, -nav h1, -section h1 { - font-size: 1.5em; - -webkit-margin-before: 0.83__qem; - -webkit-margin-after: 0.83em; +InternalEncoder.prototype.write = function(str) { + return Buffer.from(str, this.enc); } -article article h1, -article aside h1, -article nav h1, -article section h1, -aside article h1, -aside aside h1, -aside nav h1, -aside section h1, -nav article h1, -nav aside h1, -nav nav h1, -nav section h1, -section article h1, -section aside h1, -section nav h1, -section section h1 { - font-size: 1.17em; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; +InternalEncoder.prototype.end = function() { } -/* Remaining selectors are deleted because nwmatcher does not support -:matches() and expanding the selectors manually would be far too verbose. -Also see https://html.spec.whatwg.org/multipage/rendering.html#sections-and-headings -TODO: rewrite to use :matches() when nwmatcher supports it. -*/ - -h2 { - display: block; - font-size: 1.5em; - -webkit-margin-before: 0.83__qem; - -webkit-margin-after: 0.83em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold -} -h3 { - display: block; - font-size: 1.17em; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold -} +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. -h4 { - display: block; - -webkit-margin-before: 1.33__qem; - -webkit-margin-after: 1.33em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; } -h5 { - display: block; - font-size: .83em; - -webkit-margin-before: 1.67__qem; - -webkit-margin-after: 1.67em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold -} +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); -h6 { - display: block; - font-size: .67em; - -webkit-margin-before: 2.33__qem; - -webkit-margin-after: 2.33em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold + return Buffer.from(str, "base64"); } -/* tables */ - -table { - display: table; - border-collapse: separate; - border-spacing: 2px; - border-color: gray +InternalEncoderBase64.prototype.end = function() { + return Buffer.from(this.prevStr, "base64"); } -thead { - display: table-header-group; - vertical-align: middle; - border-color: inherit -} -tbody { - display: table-row-group; - vertical-align: middle; - border-color: inherit -} +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. -tfoot { - display: table-footer-group; - vertical-align: middle; - border-color: inherit +function InternalEncoderCesu8(options, codec) { } -/* for tables without table section elements (can happen with XHTML or dynamically created tables) */ -table > tr { - vertical-align: middle; +InternalEncoderCesu8.prototype.write = function(str) { + var buf = Buffer.alloc(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + } + return buf.slice(0, bufIdx); } -col { - display: table-column +InternalEncoderCesu8.prototype.end = function() { } -colgroup { - display: table-column-group -} +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ -tr { - display: table-row; - vertical-align: inherit; - border-color: inherit +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; } -td, th { - display: table-cell; - vertical-align: inherit -} +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; + } -th { - font-weight: bold + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; + } + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); + } + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; + } + } + } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; } -caption { - display: table-caption; - text-align: -webkit-center +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; } -/* lists */ -ul, menu, dir { - display: block; - list-style-type: disc; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - -webkit-padding-start: 40px -} +/***/ }), -ol { - display: block; - list-style-type: decimal; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - -webkit-padding-start: 40px -} +/***/ 26657: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -li { - display: list-item; - text-align: -webkit-match-parent; -} +"use strict"; -ul ul, ol ul { - list-style-type: circle -} +var Buffer = (__nccwpck_require__(15118).Buffer); -ol ol ul, ol ul ul, ul ol ul, ul ul ul { - list-style-type: square -} +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). -dd { - display: block; - -webkit-margin-start: 40px -} +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; + } -dl { - display: block; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; -} + this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); -dt { - display: block -} + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; -ol ul, ul ol, ul ul, ol ol { - -webkit-margin-before: 0; - -webkit-margin-after: 0 + this.encodeBuf = encodeBuf; } -/* form elements */ - -form { - display: block; - margin-top: 0__qem; -} +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; -label { - cursor: default; -} -legend { - display: block; - -webkit-padding-start: 2px; - -webkit-padding-end: 2px; - border: none +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; } -fieldset { - display: block; - -webkit-margin-start: 2px; - -webkit-margin-end: 2px; - -webkit-padding-before: 0.35em; - -webkit-padding-start: 0.75em; - -webkit-padding-end: 0.75em; - -webkit-padding-after: 0.625em; - border: 2px groove ThreeDFace; - min-width: -webkit-min-content; +SBCSEncoder.prototype.write = function(str) { + var buf = Buffer.alloc(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; } -button { - -webkit-appearance: button; +SBCSEncoder.prototype.end = function() { } -/* Form controls don't go vertical. */ -input, textarea, select, button, meter, progress { - -webkit-writing-mode: horizontal-tb !important; -} -input, textarea, select, button { - margin: 0__qem; - font: -webkit-small-control; - text-rendering: auto; /* FIXME: Remove when tabs work with optimizeLegibility. */ - color: initial; - letter-spacing: normal; - word-spacing: normal; - line-height: normal; - text-transform: none; - text-indent: 0; - text-shadow: none; - display: inline-block; - text-align: start; +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; } -/* TODO: Add " i" to attribute matchers to support case-insensitive matching */ -input[type="hidden"] { - display: none +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = Buffer.alloc(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; + } + return newBuf.toString('ucs2'); } -input { - -webkit-appearance: textfield; - padding: 1px; - background-color: white; - border: 2px inset; - -webkit-rtl-ordering: logical; - -webkit-user-select: text; - cursor: auto; +SBCSDecoder.prototype.end = function() { } -input[type="search"] { - -webkit-appearance: searchfield; - box-sizing: border-box; -} -select { - border-radius: 5px; -} +/***/ }), -textarea { - -webkit-appearance: textarea; - background-color: white; - border: 1px solid; - -webkit-rtl-ordering: logical; - -webkit-user-select: text; - flex-direction: column; - resize: auto; - cursor: auto; - padding: 2px; - white-space: pre-wrap; - word-wrap: break-word; -} +/***/ 21012: +/***/ ((module) => { -input[type="password"] { - -webkit-text-security: disc !important; -} +"use strict"; -input[type="hidden"], input[type="image"], input[type="file"] { - -webkit-appearance: initial; - padding: initial; - background-color: initial; - border: initial; -} -input[type="file"] { - align-items: baseline; - color: inherit; - text-align: start !important; +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } } -input[type="radio"], input[type="checkbox"] { - margin: 3px 0.5ex; - padding: initial; - background-color: initial; - border: initial; -} +/***/ }), -input[type="button"], input[type="submit"], input[type="reset"] { - -webkit-appearance: push-button; - -webkit-user-select: none; - white-space: pre -} +/***/ 41080: +/***/ ((module) => { -input[type="button"], input[type="submit"], input[type="reset"], button { - align-items: flex-start; - text-align: center; - cursor: default; - color: ButtonText; - padding: 2px 6px 3px 6px; - border: 2px outset ButtonFace; - background-color: ButtonFace; - box-sizing: border-box -} +"use strict"; -input[type="range"] { - -webkit-appearance: slider-horizontal; - padding: initial; - border: initial; - margin: 2px; - color: #909090; -} -input[type="button"]:disabled, input[type="submit"]:disabled, input[type="reset"]:disabled, -button:disabled, select:disabled, optgroup:disabled, option:disabled, -select[disabled]>option { - color: GrayText -} +// Manually added data to be used by sbcs codec in addition to generated one. -input[type="button"]:active, input[type="submit"]:active, input[type="reset"]:active, button:active { - border-style: inset -} +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, -input[type="button"]:active:disabled, input[type="submit"]:active:disabled, input[type="reset"]:active:disabled, button:active:disabled { - border-style: outset -} + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, -datalist { - display: none -} + "mik": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, -area { - display: inline; - cursor: pointer; -} + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", -param { - display: none -} + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", -input[type="checkbox"] { - -webkit-appearance: checkbox; - box-sizing: border-box; -} + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", -input[type="radio"] { - -webkit-appearance: radio; - box-sizing: border-box; -} + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", -input[type="color"] { - -webkit-appearance: square-button; - width: 44px; - height: 23px; - background-color: ButtonFace; - /* Same as native_theme_base. */ - border: 1px #a9a9a9 solid; - padding: 1px 2px; -} + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", -input[type="color"][list] { - -webkit-appearance: menulist; - width: 88px; - height: 23px -} + "cp819": "iso88591", + "ibm819": "iso88591", -select { - -webkit-appearance: menulist; - box-sizing: border-box; - align-items: center; - border: 1px solid; - white-space: pre; - -webkit-rtl-ordering: logical; - color: black; - background-color: white; - cursor: default; -} + "cyrillic": "iso88595", -optgroup { - font-weight: bolder; - display: block; -} + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", -option { - font-weight: normal; - display: block; - padding: 0 2px 1px 2px; - white-space: pre; - min-height: 1.2em; -} + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", -output { - display: inline; -} + "hebrew": "iso88598", + "hebrew8": "iso88598", -/* meter */ + "turkish": "iso88599", + "turkish8": "iso88599", -meter { - -webkit-appearance: meter; - box-sizing: border-box; - display: inline-block; - height: 1em; - width: 5em; - vertical-align: -0.2em; -} + "thai": "iso885911", + "thai8": "iso885911", -/* progress */ + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", -progress { - -webkit-appearance: progress-bar; - box-sizing: border-box; - display: inline-block; - height: 1em; - width: 10em; - vertical-align: -0.2em; -} + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", -/* inline elements */ + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", -u, ins { - text-decoration: underline -} + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", -strong, b { - font-weight: bold -} + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", -i, cite, em, var, address, dfn { - font-style: italic -} + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", -tt, code, kbd, samp { - font-family: monospace -} + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", -pre, xmp, plaintext, listing { - display: block; - font-family: monospace; - white-space: pre; - margin: 1__qem 0 -} + "strk10482002": "rk1048", -mark { - background-color: yellow; - color: black -} + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", -big { - font-size: larger -} + "gb198880": "iso646cn", + "cn": "iso646cn", -small { - font-size: smaller -} + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", -s, strike, del { - text-decoration: line-through -} + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", -sub { - vertical-align: sub; - font-size: smaller -} + "mac": "macintosh", + "csmacintosh": "macintosh", +}; -sup { - vertical-align: super; - font-size: smaller -} -nobr { - white-space: nowrap -} -/* states */ +/***/ }), -:focus { - outline: auto 5px -webkit-focus-ring-color -} +/***/ 11155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* Read-only text fields do not show a focus ring but do still receive focus */ -html:focus, body:focus, input[readonly]:focus { - outline: none -} +"use strict"; -embed:focus, iframe:focus, object:focus { - outline: none -} +var Buffer = (__nccwpck_require__(15118).Buffer); -input:focus, textarea:focus, select:focus { - outline-offset: -2px -} +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js -input[type="button"]:focus, -input[type="checkbox"]:focus, -input[type="file"]:focus, -input[type="hidden"]:focus, -input[type="image"]:focus, -input[type="radio"]:focus, -input[type="reset"]:focus, -input[type="search"]:focus, -input[type="submit"]:focus { - outline-offset: 0 +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { } -/* HTML5 ruby elements */ +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; -ruby, rt { - text-indent: 0; /* blocks used for ruby rendering should not trigger this */ -} -rt { - line-height: normal; - -webkit-text-emphasis: none; +// -- Encoding + +function Utf16BEEncoder() { } -ruby > rt { - display: block; - font-size: 50%; - text-align: start; +Utf16BEEncoder.prototype.write = function(str) { + var buf = Buffer.from(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; + } + return buf; } -ruby > rp { - display: none; +Utf16BEEncoder.prototype.end = function() { } -/* other elements */ -noframes { - display: none -} +// -- Decoding -frameset, frame { - display: block +function Utf16BEDecoder() { + this.overflowByte = -1; } -frameset { - border-color: inherit -} +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; -iframe { - border: 2px inset -} + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, j = 0; -details { - display: block -} + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; + } -summary { - display: block + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); } -template { - display: none +Utf16BEDecoder.prototype.end = function() { } -bdi, output { - unicode-bidi: -webkit-isolate; + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; } -bdo { - unicode-bidi: bidi-override; +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; + + +// -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); } -textarea[dir=auto] { - unicode-bidi: -webkit-plaintext; +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); } -dialog:not([open]) { - display: none +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); } -dialog { - position: absolute; - left: 0; - right: 0; - width: -webkit-fit-content; - height: -webkit-fit-content; - margin: auto; - border: solid; - padding: 1em; - background: white; - color: black + +// -- Decoding + +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; + + this.options = options || {}; + this.iconv = codec.iconv; } -[hidden] { - display: none +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + + if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + this.initialBytes.length = this.initialBytesLen = 0; + } + + return this.decoder.write(buf); } -/* noscript is handled internally, as it depends on settings. */ +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); -`; + var res = this.decoder.write(buf), + trail = this.decoder.end(); + return trail ? (res + trail) : res; + } + return this.decoder.end(); +} -/***/ }), +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; -/***/ 42751: -/***/ ((module) => { + if (buf.length >= 2) { + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM + enc = 'utf-16be'; + else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM + enc = 'utf-16le'; + else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions + _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. -"use strict"; + for (var i = 0; i < _len; i += 2) { + if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; + if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; + } + if (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; + } + } -module.exports = function (nameForErrorMessage, window) { - if (!window) { - // Do nothing for window-less documents. - return; - } + return enc; +} - const error = new Error(`Not implemented: ${nameForErrorMessage}`); - error.type = "not implemented"; - window._virtualConsole.emit("jsdomError", error); -}; /***/ }), -/***/ 53601: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 51644: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +var Buffer = (__nccwpck_require__(15118).Buffer); -const parse5 = __nccwpck_require__(65598); +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 -const { createElement } = __nccwpck_require__(98548); -const { HTML_NS } = __nccwpck_require__(52635); +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; -const DocumentType = __nccwpck_require__(53193); -const DocumentFragment = __nccwpck_require__(11490); -const Text = __nccwpck_require__(49374); -const Comment = __nccwpck_require__(56625); +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; -const attributes = __nccwpck_require__(35092); -const nodeTypes = __nccwpck_require__(10656); -const serializationAdapter = __nccwpck_require__(19756); -const { - customElementReactionsStack, invokeCEReactions, lookupCEDefinition -} = __nccwpck_require__(25392); +// -- Encoding -// Horrible monkey-patch to implement https://github.com/inikulin/parse5/issues/237 and -// https://github.com/inikulin/parse5/issues/285. -const OpenElementStack = __nccwpck_require__(64813); +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; -const openElementStackOriginalPush = OpenElementStack.prototype.push; -OpenElementStack.prototype.push = function (...args) { - openElementStackOriginalPush.apply(this, args); - this.treeAdapter._currentElement = this.current; +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} - const after = this.items[this.stackTop]; - if (after._pushedOnStackOfOpenElements) { - after._pushedOnStackOfOpenElements(); - } -}; +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return Buffer.from(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} -const openElementStackOriginalPop = OpenElementStack.prototype.pop; -OpenElementStack.prototype.pop = function (...args) { - const before = this.items[this.stackTop]; +Utf7Encoder.prototype.end = function() { +} - openElementStackOriginalPop.apply(this, args); - this.treeAdapter._currentElement = this.current; - if (before._poppedOffStackOfOpenElements) { - before._poppedOffStackOfOpenElements(); - } -}; +// -- Decoding -class JSDOMParse5Adapter { - constructor(documentImpl, options = {}) { - this._documentImpl = documentImpl; - this._globalObject = documentImpl._globalObject; - this._fragment = options.fragment || false; +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} - // Since the createElement hook doesn't provide the parent element, we keep track of this using _currentElement: - // https://github.com/inikulin/parse5/issues/285. See above horrible monkey-patch for how this is maintained. - this._currentElement = undefined; - } +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); - _ownerDocument() { - const { _currentElement } = this; +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); - // The _currentElement is undefined when parsing elements at the root of the document. - if (_currentElement) { - return _currentElement.localName === "template" && _currentElement.namespaceURI === HTML_NS ? - _currentElement.content._ownerDocument : - _currentElement._ownerDocument; - } +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; - return this._documentImpl; - } + // The decoder is more involved as we must handle chunks in stream. - createDocument() { - // parse5's model assumes that parse(html) will call into here to create the new Document, then return it. However, - // jsdom's model assumes we can create a Window (and through that create an empty Document), do some other setup - // stuff, and then parse, stuffing nodes into that Document as we go. So to adapt between these two models, we just - // return the already-created Document when asked by parse5 to "create" a Document. - return this._documentImpl; - } + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } - createDocumentFragment() { - const ownerDocument = this._ownerDocument(); - return DocumentFragment.createImpl(this._globalObject, [], { ownerDocument }); - } + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; - // https://html.spec.whatwg.org/#create-an-element-for-the-token - createElement(localName, namespace, attrs) { - const ownerDocument = this._ownerDocument(); + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } - const isAttribute = attrs.find(attr => attr.name === "is"); - const isValue = isAttribute ? isAttribute.value : null; + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); - const definition = lookupCEDefinition(ownerDocument, namespace, localName); + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); - let willExecuteScript = false; - if (definition !== null && !this._fragment) { - willExecuteScript = true; + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } - if (willExecuteScript) { - ownerDocument._throwOnDynamicMarkupInsertionCounter++; - customElementReactionsStack.push([]); - } + this.inBase64 = inBase64; + this.base64Accum = base64Accum; - const element = createElement(ownerDocument, localName, namespace, null, isValue, willExecuteScript); - this.adoptAttributes(element, attrs); + return res; +} - if (willExecuteScript) { - const queue = customElementReactionsStack.pop(); - invokeCEReactions(queue); - ownerDocument._throwOnDynamicMarkupInsertionCounter--; - } +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - if ("_parserInserted" in element) { - element._parserInserted = true; - } + this.inBase64 = false; + this.base64Accum = ''; + return res; +} - return element; - } - createCommentNode(data) { - const ownerDocument = this._ownerDocument(); - return Comment.createImpl(this._globalObject, [], { data, ownerDocument }); - } +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. - appendChild(parentNode, newNode) { - parentNode._append(newNode); - } - insertBefore(parentNode, newNode, referenceNode) { - parentNode._insert(newNode, referenceNode); - } +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; +}; - setTemplateContent(templateElement, contentFragment) { - // This code makes the glue between jsdom and parse5 HTMLTemplateElement parsing: - // - // * jsdom during the construction of the HTMLTemplateElement (for example when create via - // `document.createElement("template")`), creates a DocumentFragment and set it into _templateContents. - // * parse5 when parsing a